1.委托与事件的区别
事件对权限做了控制
1.委托可以直接调用
事件不可以直接调用
2.委托允许外面直接赋值
事件不允许外面直接赋值
2.事件与委托的实例比较
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyEvent { //委托的声明 public delegate void DoSometing(); /// <summary> /// 委托与事件的关系 /// 委托是一种类型 /// 事件是委托的一个实例 /// </summary> public class MyEvent { public DoSometing doSomethingDelegate;//委托的一个变量 public event DoSometing doSomethingEvent;//一个事件,就是委托的一个变量,加上了event关键字 //事件的使用 public void InvokeEvent() { Console.WriteLine("------------InvokeEvent------------"); if (doSomethingEvent != null) { doSomethingEvent(); } } public void InvokeDelegate() { Console.WriteLine("------------InvokeDelegate------------"); if (doSomethingDelegate != null) { doSomethingDelegate(); } } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyEvent { class Program { static void Main(string[] args) { Console.WriteLine("欢迎来到流星小子博客学习"); MyEvent myEvent = new MyEvent(); myEvent.doSomethingEvent += ShowSomething;//为事件实例化 myEvent.doSomethingEvent += ShowSomething;//为事件实例化 //事件不可以直接调用 //myEvent.doSomethingEvent(); //事件不允许外面直接赋值 //myEvent.doSomethingEvent = ShowSomething; myEvent.doSomethingEvent += ShowSomething;//为事件实例化 myEvent.doSomethingEvent += ShowSomething;//为事件实例化 myEvent.doSomethingEvent -= ShowSomething;//为事件实例化 myEvent.InvokeEvent();//触发事件 myEvent.doSomethingDelegate += ShowSomething; myEvent.doSomethingDelegate += ShowSomething; myEvent.doSomethingDelegate += ShowSomething; //委托可以直接调用 myEvent.doSomethingDelegate(); //委托允许外面直接赋值 myEvent.doSomethingDelegate = ShowSomething; myEvent.doSomethingDelegate += ShowSomething; myEvent.doSomethingDelegate -= ShowSomething; myEvent.InvokeDelegate(); Console.Read(); } private static void ShowSomething() { Console.WriteLine("ShowSomething"); } } }
时间: 2024-10-16 22:08:43