C#中的Delegate機制(Delegate in C#)

暑期閒來無事,翻了翻《C#入門經典》一書,對個人認爲比較重要或者我們經常比較容易忽略或遺忘的東西,做了一些讀書筆記。今天對其中的一些內容做一個簡單的整理,一方面自己再加深一遍印象,同時,也希望對讀者有所幫助。

今日關鍵詞:Delegate

一、是什麼?

Definition: A delegate is a type that enables you to store references to functions.
首先這句話告訴我們Delegate是指一種type,這種特殊的type能實現可以作爲function的參數使用。可是Delegate作爲參數有什麼好處呢,我們帶着疑問繼續下面的學習。

備註:Functions in C# are a means of providing blocks of code that can be executed at any point in an application。


二、怎麼用

Delegate的申明:

Delegates的申明和Function的申明相似,但Delegates沒有方法體,通過delegate關鍵字進行申明。
申明格式:delegate [return type] [delegateName](type1 param1, type2 param2 ...)

   After defining a delegate, you can declare a variable with the type of that delegate. You can then initialize this variable as a reference to any function that has the same signature as that delegate. Once you have done this, you can call that function by using the delegate variable as if it were a function.
When you have a variable that refers to a function, you can also perform other operations that would be impossible by any other means. For example, you can pass a delegate variable to a function as a parameter, then that function can use the delegate to call whatever function it refers to, without having knowledge as to what function will be called until runtime.

 

看下面一個例子:

有兩個數,現在需要完成這兩個數的一種運算,可能是加減乘除,也可能是其他,然後返回計算結果。


        delegate double CalculateDelegate(double one, double another);
        static double Divide(double one, double another)
        {
            return one / another;
        }

        static double Add(double one, double another)
        {
            return one + another;
        }
         
        static double ExcuteCalculate(CalculateDelegate c);
        
        public static void main(){
            CalculateDelegate cal = new CalculateDelegate(Divide)
          
            //use the delegate variable like a function
            double result0 = cal(2.1,3.14);
          
            //use the delegate reference as a function parameter  
            double result = ExecuteCalculate(cal);
            Console.WriteLine("=========================================");
            Console.WriteLine("【第一種方式】2.1與3.14相除的結果是:{0}",result0);
            Console.WriteLine("【第二種方式】2.1與3.14相除的結果是:{0}",result);
            Console.WriteLine("=========================================");
            Console.ReadKey()
}




發佈了36 篇原創文章 · 獲贊 5 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章