委托是一种引用类型,可以将方法作为参数传递给其他方法,作为参数的这个方法可以是静态方法,实例方法,也可以是匿名方法。这种能力使委托成为定义回调方法的理想选择。
- 委托和方法必须具有相同的方法签名
- 委托可以连在一起,例如可以对一个事件调用多个方法,称为多播
- 由于委托派生自 System.Delegate ,因此可以在委托实例对象上调用该类的方法和属性。例如,获取委托调用列表中方法的数量:delegateObj.GetInvocationList().GetLength(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);
// 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); };
网友评论