欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

委托(delegate)的C#版本不同赋值 delegate 

程序员文章站 2022-07-12 19:51:12
...

1、在 C# 1.0 和更高版本中,可以如下面的示例所示声明委托。

// Declare a delegate.
delegate void Del(string str);

// Declare a method with the same signature as the delegate.
static void Notify(string name)
{
    Console.WriteLine("Notification received for: {0}", name);
}

 

// Create an instance of the delegate.
Del del1 = new Del(Notify);

 2、C# 2.0 提供了更简单的方法来编写前面的声明,如下面的示例所示。

// C# 2.0 provides a simpler way to declare an instance of Del.
Del del2 = Notify;

 3、在 C# 2.0 和更高版本中,还可以使用匿名方法来声明和初始化委托,如下面的示例所示。

// Instantiate Del by using an anonymous method.
Del del3 = delegate(string name)
    { Console.WriteLine("Notification received for: {0}", name); };

 4、在 C# 3.0 和更高版本中,还可以通过使用 lambda 表达式声明和实例化委托,如下面的示例所示。

// Instantiate Del by using a lambda expression.
Del del4 = name =>  { Console.WriteLine("Notification received for: {0}", name); };

 

相关标签: delegate