一、什么是委托?

委托类型声明的格式如下:

  //申明委托
   public delegate void TestDelegate(string message);

1.delegate 关键字用于声明一个引用类型,该引用类型可用于封装命名方法或匿名方法。委托是类型安全和可靠的。

2.委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值,如下面的示例所示:

3.委托具有以下特点:

  • 委托类似于 C++ 函数指针,但它是类型安全的。

  • 委托允许将方法作为参数进行传递。

  • 委托可用于定义回调方法。

  • 委托可以链接在一起;例如,可以对一个事件调用多个方法。

  • 方法不需要与委托签名精确匹配。有关更多信息,请参见协变和逆变

  • C# 2.0 版引入了匿名方法的概念,此类方法允许将代码块作为参数传递,以代替单独定义的方法。

二、委托在.net中的几种写法

1.在.net 1.0中的写法如下:

View Code
 //申明委托签名
 public delegate void TestDelegate(string message);
//委托的匹配方法
  public static void TestMethod(string msg)
        {
            Console.WriteLine(
string.Format(".net 委托:{0}", msg));
        }

  
static void Main(string[] args)
        {
            
#region .net 1.x写法
            TestDelegate dele1 
= TestMethod;
            dele1(
".net 1.x写法");

            TestDelegate dele2 
= new TestDelegate(TestMethod);
            dele2(
".net 1.x写法");
            
#endregion
     }

2.在.net 2.0中的写法,.net 2.0中重要的是引入了匿名方法,  当然也可以使用.net1.0中的写法。


#region .net2.x写法
static void Main(string[] args)
{
  
//申明委托对象的时候直接指向一个方法(匿名)的实现
   TestDelegate dele3 = delegate(string msg)
             {
                 Console.WriteLine(
string.Format(".Net委托:{0}", msg));
             };
             dele3(
".net2.x写法--匿名方法");
}

相关文章:

  • 2021-06-06
  • 2021-11-04
  • 2021-11-10
  • 2021-10-18
  • 2022-12-23
猜你喜欢
  • 2021-12-13
  • 2021-08-28
  • 2021-07-21
  • 2021-12-01
  • 2021-10-09
  • 2021-06-19
  • 2021-05-31
相关资源
相似解决方案