delegate 是表示对具有特定参数列表和返回类型的方法的引用的类型. 在实例化委托时, 你可以将其实例与任何具有兼容签名和返回类型的方法相关联. 你可以通过委托实例调用方法.
委托用于将方法作为参数传递给其他方法. 事件处理程序就是通过委托调用的方法. 你可以创建一个自定义方法, 当发生特定事件时, 某个类 (如 Windows 控件) 就可以调用你的方法(举个例子, Winform 上拖拽完 button, 然后双击, 后台生成这个 button 的点击事件, 这样这个 button 的点击事件就跟你的方法绑定起来了).
需求: 遇到到不同国家的人, 以不同方式跟他打招呼.
Talking is easy ,show me the codes .
- namespace ConsoleDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- List<People> pp = new List<People>();
- pp.Add(new People { Name = "马大云", Country = "中国" });
- pp.Add(new People { Name = "Bill Gat", Country = "USA" });
- pp.ForEach(p => Say(p));
- }
- public static void Say(People p)
- {
- if (p != null && !string.IsNullOrEmpty(p.Country))
- {
- if (p.Country.Equals("中国", StringComparison.OrdinalIgnoreCase))
- {
- Chinesenihao(p.Name);
- }
- if (p.Country.Equals("USA", StringComparison.OrdinalIgnoreCase))
- {
- EnglishHello(p.Name);
- }
- }
- }
- public static void Chinesenihao(string name)
- {
- Console.WriteLine($"{name}, 老表, 吃饭没?");
- }
- public static void EnglishHello(string name)
- {
- Console.WriteLine($"hi,{name},the weather is nice today.");
- }
- }
- public class People
- {
- public string Name { get; set; }
- public string Country { get; set; }
- }
- }
上面这种实现是可以的, 满足了需求, 当再来几个国家, Say 方法里面再加几个就阔以了.
但是当你工作几年后, 你还这么写, 那就不清真 (zhuang bi shi bai ) 了.
Talking is easy ,show me the codes .
- public delegate void sayhellodelegate(string name);
- class Program
- {
- static void Main(string[] args)
- {
- List<People> pp = new List<People>();
- pp.Add(new People { Name = "马大云", Country = "中国" ,sayfunction= Chinesenihao });
- pp.Add(new People { Name = "Bill Gat", Country = "USA" ,sayfunction= EnglishHello });
- pp.ForEach(p => Say(p));
- }
- public static void Say(People p)
- {
- p.sayfunction(p.Name);
- }
- public static void Chinesenihao(string name)
- {
- Console.WriteLine($"{name}, 老表, 吃饭没?");
- }
- public static void EnglishHello(string name)
- {
- Console.WriteLine($"hi,{name},the weather is nice today.");
- }
- }
- public class People
- {
- public string Name { get; set; }
- public string Country { get; set; }
- public sayhellodelegate sayfunction { get; set; }
- }
上面的代码中, sayhellodelegate 当做一种类型在用. 这也是为什么文章开头的那句是这样的: delegate 是表示对具有特定参数列表和返回类型的方法的引用的类型.
新需求: 遇到到不同国家的人, 以不同方式跟他打招呼, 如果有多个国家的国籍, 择使用多种方式打招呼.
- static void Main(string[] args)
- {
- List<People> pp = new List<People>();
- var t = new People { Name = "马大云", Country = "中国", sayfunction = Chinesenihao };
- t.Country = "中国, USA";
- t.sayfunction += EnglishHello;
- pp.Add(t);
- pp.Add(new People { Name = "Bill Gat", Country = "USA", sayfunction = EnglishHello });
- pp.ForEach(p => Say(p));
- }
其他代码不动, 在给 Sayfunction 赋值时坐了追加就满足了需求.
这是 delegate 的另外一个特性:
可以将多个方法赋给同一个委托, 或者叫将多个方法绑定到同一个委托, 当调用这个委托的时候, 将依次调用其所绑定的方法.
当然可以追加, 也可以取消.
使用委托可以将多个方法绑定到同一个委托变量, 当调用此变量时(这里用 "调用" 这个词, 是因为此变量代表一个方法), 可以依次调用所有绑定的方法.
来源: https://www.cnblogs.com/kim-meng/p/11473883.html