美文网首页
C# 委托(delegate)

C# 委托(delegate)

作者: CodeVin | 来源:发表于2019-03-22 18:47 被阅读0次

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

  • 委托和方法必须具有相同的方法签名
  • 委托可以连在一起,例如可以对一个事件调用多个方法,称为多播
  • 由于委托派生自 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); };

相关文章

  • C# 委托

    C#委托 C#中的委托(Delegate)类似于C或C++中函数的指针。委托(Delegate)是存有对某个方法的...

  • C# 高级语言总结

    后续 1 C# 委托 委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 ...

  • C#委托Delegate和事件Event实战应用

    一、委托的概念 C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate)是...

  • C# 委托(Delegate)

    C# 中的委托(Delegate)类似于 C 或 C++ 中的函数指针。委托(Delegate) 是存有对某个方法...

  • 19-委托

    C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。 委托(Delegate) 是存有对某个方...

  • C# 委托(delegate)

    委托是一种引用类型,可以将方法作为参数传递给其他方法,作为参数的这个方法可以是静态方法,实例方法,也可以是匿名方法...

  • C# delegate

    C# 中的 Delegate 类似于 C++ 中函数的指针。所有的委托Delegate都派生自 System.De...

  • 关于C#中的委托与事件以及两者之间的关系

    一 关于委托 1.委托的概念: C# 中的委托(Delegate)是一种引用类型变量,它类似于C的函数指针,...

  • C#之delegate(委托)

    定义 委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做...

  • 52个有效方法(23) - 通过委托与数据协议进行对象间的通信

    委托模式(Delegate pattern) 委托模式(Delegate pattern):用来实现对象间的通信 ...

网友评论

      本文标题:C# 委托(delegate)

      本文链接:https://www.haomeiwen.com/subject/gtwrvqtx.html