C# 委托(delegate)

2019-03-22  本文已影响0人  CodeVin

委托是一种引用类型,可以将方法作为参数传递给其他方法,作为参数的这个方法可以是静态方法,实例方法,也可以是匿名方法。这种能力使委托成为定义回调方法的理想选择。

如何:声明,实例化和使用委托

// 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);

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

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

// C# 3.0 Instantiate Del by using a lambda expression.
Del del4 = name =>  { Console.WriteLine("Notification received for: {0}", name); };
上一篇 下一篇

猜你喜欢

热点阅读