C#學習重要概念之委託(delegate)

委託類型的聲明與方法簽名類似,  有一個返回值和任意數目任意類型的參數:express

public delegate void TestDelegate(string message);  
public delegate int TestDelegate(MyType m, long num);

delegate 是一種可用於封裝命名或匿名方法的引用類型。  委託相似於 C++ 中的函數指針;可是,委託是類型安全和可靠的。  有關委託的應用,請參見委託泛型委託安全

備註ide

委託是事件的基礎。函數

經過將委託與命名方法或匿名方法關聯,能夠實例化委託。  有關更多信息,請參見命名方法匿名方法ui

必須使用具備兼容返回類型和輸入參數的方法或 lambda 表達式實例化委託。  有關方法簽名中容許的差別程度的更多信息,請參見委託中的變體。  爲了與匿名方法一塊兒使用,委託和與之關聯的代碼必須一塊兒聲明。  本節討論這兩種實例化委託的方法。spa

示例指針

  // Declare delegate -- defines required signature:
    delegate double MathAction(double num);   
     class DelegateTest
    {        
    // Regular method that matches signature:
        static double Double(double input)        
        {            
        return input * 2;
        }        
        static void Main()
        {            
        // Instantiate delegate with named method:
            MathAction ma = Double;           
             // Invoke delegate ma:
            double multByTwo = ma(4.5);
            Console.WriteLine("multByTwo: {0}", multByTwo);            
            // Instantiate delegate with anonymous method:
            MathAction ma2 = delegate(double input)
            {                
            return input * input;
            };            
            double square = ma2(5);
            Console.WriteLine("square: {0}", square);           
             // Instantiate delegate with lambda expression
            MathAction ma3 = s => s * s * s;           
             double cube = ma3(4.375);

            Console.WriteLine("cube: {0}", cube);
        }        
        // Output:
        // multByTwo: 9
        // square: 25
        // cube: 83.740234375
    }


C# 語言規範code

有關詳細信息,請參閱 C# 語言規範。 該語言規範是 C# 語法和用法的權威資料。事件

備註:轉自https://msdn.microsoft.com/zh-cn/library/900fyy8e.aspx
get

相關文章
相關標籤/搜索