事件是委托的一个实例 小明是一个实例;1.事件不能被初始化 (防止外面直接赋值为 null 导致注册失败) 2.不能被外部调用
委托是一种类型 People是一个类型
namespace 委托学习{ class Program { static void Main(string[] args) { //MyDelegate.Show();
//不使用委托 耦合的东西太多, GreetingClass.Greeting("猪八戒", 委托学习.GreetingClass.PeopleType.Chinese);
//使用委托 1.实例化委托 解耦 职责单一 委托学习.GreetingClass.GreetingHandle handle = new GreetingClass.GreetingHandle(GreetingClass.GreetingChinese); handle.Invoke("666");//方法的调用 GreetingClass.Greeting("猪猪猪",handle); Console.ReadLine();
//本质完全不同 //程序通过添加代码就可以实现功能,而不是修改代码===》》对扩展是开发的 对修改封闭的 //如果添加一个日本人,直接添加一个GretingJapanese的方法就好了 } }}
=======================================================================================
namespace 委托学习{ //1.声明 2.实例化 3.调用 //委托可以处于Class之外 public delegate void OutNoResultNoPara();//无返回值 public delegate void OutNoResultWithPara(int x, int y);// public class MyDelegate { public delegate void NoResultNoPara(); public delegate void NoResultWithPara(int x, int y);//
public delegate string NoPara(); public delegate DateTime WithPara(string name, int size);
public static void Show() { Student stu = new Student(); stu.Id = 123; stu.Name = "eleven"; stu.Study();
//委托其实和类一样,也可以进行实例化 NoResultWithPara method = new NoResultWithPara(Puls);//委托的实例化===是一个void 俩个参数的参数传入 NoResultWithPara method1 = Puls;//简写的方式 method.Invoke(1, 3);//委托的调用==method(2,6); 二者完全等价 method.BeginInvoke(3, 8, null, null);//异步调用,就是另外开启一个线程去调用 //没有委托是没有异步的
}
public static void Puls(int x,int y) { Console.WriteLine("这里是Plusx={0},y={1}",x,y); }
}}
========================================================================================
namespace 委托学习{ public class GreetingClass {
public static void GreetingChinese(string name) { Console.WriteLine("早上好,{0}", name); }
public static void GreetingEnglish(string name) { Console.WriteLine("Good Morning{0}", name); }
public static void Greeting(string name, PeopleType type) { if (type == PeopleType.American) { Console.WriteLine("Good Morning{0}",name); } else if (type == PeopleType.Chinese) { Console.WriteLine("早上好,{0}", name); } else { throw new Exception("人物类型错误"); }
}
public static void Greeting(string name,GreetingHandle handler) {
handler.Invoke(name); } //在这个委托里,传入了一个string类型的name参数,在实例化他的时候,能够点出来所有的带有string类型的name参数的方法 public delegate void GreetingHandle(string name); public enum PeopleType { American, Chinese } }}
转载于:https://www.cnblogs.com/ZkbFighting/p/7638150.html
相关资源:数据结构—成绩单生成器