委托类型的声明与方法签名相似, 有一个返回值和任意数目任意类型的参数:- public delegate void TestDelegate(string message);
- public delegate int TestDelegate(MyType m, long num);
复制代码 delegate 是一种可用于封装命名或匿名方法的引用类型。 委托类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。
给你个例子看看:
- // 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
- }
复制代码 我刚开始学委托的时候也很难理解,这个要多做练习才能慢慢理解 |