委托是C#中非常重要的一个概念,并在C#中得到了丰富的应用,如事件,线程等。那什么是委托呢?具体来说,委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值。
委托具有以下特点:
委托类似于 C++(www.cppentry.com) 函数指针,但它是类型安全的。
委托允许将方法作为参数进行传递。
委托可用于定义回调方法。
委托可以链接在一起;例如,可以对一个事件调用多个方法。
方法不需要与委托签名精确匹配。有关更多信息,请参见协变和逆变。
C# 2.0 版引入了匿名方法的概念,此类方法允许将代码块作为参数传递,以代替单独定义的方法。
在C#中使用委托分为三步:
1.定义委托:
-
- public delegate void MyDel();
2.实例化委托:
- TestDel t = new TestDel();
- Console.WriteLine("-----以下是简单使用委托演示--------");
-
-
-
- MyDel del = new MyDel(t.MyMethod);
3.调用委托:
-
- del();
好了,其实委托的变化很复杂,但基本都会符合这么三个步骤,说过了,这些,再来看一下完整的代码:
- namespace DelegateDemo{
-
- public delegate void MyDel();
-
- public delegate void MyDel2(int num1, int num2);
-
- public delegate string MyDel3(string s);
-
- public delegate string ProcessString(string s);
- class Program { static void Main(string[] args)
- { #region 委托演示
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #endregion
-
-
- MyParamDelegateTest myParam = new MyParamDelegateTest(); myParam.AddBooks();
- myParam.MyTest();
- } }
- public class TestDel {
- #region 普通方法
- public static void MyStaticMethod()
- {
- Console.WriteLine("My Static Method");
- }
- public void MyMethod()
- {
- Console.WriteLine("MyMethod");
- }
- public void MyMethod2()
- {
- Console.WriteLine("My Method 22222222222"); }
- public static void MyMethod3()
- {
- Console.WriteLine("My Method 3333333333333");
- }
- public void MyMethod(int num1, int num2) { Console.WriteLine(num1+num2);
- }
- public string MyMethod(string s)
- { return s.ToUpper(); }
- #endregion
-
-
-
-
-
- public static void MyParamMethod(string s, MyDel3 del3) { Console.WriteLine(del3(s)); }
-
-
-
-
-
-
- return MyMethod;
- }
- }
-
通过例子,我们可以知道,使用委托可以将多个方法绑定到同一个委托变量,当调用此变量时(这里用“调用”这个词,是因为此变量代表一个方法),可以依次调用所有绑定的方法。
【编辑推荐】
- 细说C++(www.cppentry.com)委托和消息反馈模板
- 详解C#基础之委托异步
- 详解C#委托、时间和Lambda表达式
- 详解.NET中容易混淆的委托与接口