Delegate, Event Delegate其实就相当于C++/C里面的函数指针.用法如下: 1.最常规的使用 class Program { public delegate void NumberChangedEventHandler(int number); class Publisher { public NumberChangedEventHandler NumberChanged; } class Subscriber { public void OnNumberChanged(int number) { string message = "New value is " + number; Console.WriteLine(message); } } static void Main(string[] args) { Publisher pub = new Publisher(); Subscriber sub1 = new Subscriber(); Subscriber sub2 = new Subscriber(); pub.NumberChanged += new NumberChangedEventHandler(sub1.OnNumberChanged); pub.NumberChanged += new NumberChangedEventHandler(sub2.OnNumberChanged); pub.NumberChanged(3); Console.WriteLine("over"); } } 2.直接当成函数指针用 class Program { public delegate void NumberChangedEventHandler(int number); class Publisher { public NumberChangedEventHandler NumberChanged; } class Subscriber { public void OnNumberChanged(int number) { string message = "New value is " + number; Console.WriteLine(message); } } static void Main(string[] args) { Publisher pub = new Publisher(); Subscriber sub1 = new Subscriber(); pub.NumberChanged = sub1.OnNumberChanged; pub.NumberChanged(3); } } 3.异步调用 class Program { public delegate void NumberChangedEventHandler(int number); class Publisher { public NumberChangedEventHandler NumberChanged; } class Subscriber { public void OnNumberChanged(int number) { string message = "New value is " + number; Console.WriteLine(message); } } static void Main(string[] args) { Publisher pub = new Publisher(); Subscriber sub1 = new Subscriber(); pub.NumberChanged += new NumberChangedEventHandler(sub1.OnNumberChanged); pub.NumberChanged.BeginInvoke(3, null, null); } }
C# Delegate 使用
原创皮尔兄弟 ©著作权
文章标签 C# delegate 文章分类 C/C++ 后端开发
-
#yyds干货盘点#C#高级特性——delegate使用
C#高级特性【delegate】委托的用法
调用方法 参数传递 引用类型 委托 -
C# -- delegate 与 event 解析
/// <summary
ide 初始化 成员方法 -
C#基础:委托(Delegate)详解
在C#中,定义一个委托类型需要指定其参数类型和返回类型。public delegate 返回类型 委托名(参数类型 参数名[, ...]);
c# 开发语言 匿名方法 lambda表达式 事件处理 -
C#中的Delegate
C#中的Delegate
c# hive html JAVA