We can call callback methods using delegates. For eg,
public delegate bool ContinueProcessing();
// later in code we can write ,
ContinueProcessing cp = new ContinueProcessing(IsDataAvailable);
cp += new ContinueProcessing(IsTransactionComplete);
//later in code defination of methods
bool IsDataAvailable() { return true; }
bool IsTransactionComplete() { return true; }
cp.Invoke() ;
The above call will call two boolean method one after the other. Why we need "Events" ? What is the purpose of "Events" ?
Events are callbacks where you can have multiple subscribers who don't interfere with each other and can't call each other.
Delegates provide the encapsulation of "this is the action I want to take" and events provide the encapsulation of the pub/sub model.
See my article on events for more information.
Delegates are very generic. They can be used in any context: within the same class, between classes, in static methods etc.
Events are more specific -- they are specifically designed to be used for one class to subscribe to an event raised by another class.
Delegate is a (kind of) type-safe pointer to a function, whereas event is wrapper around delegate that provides standard interface to Subscribe/Unsubscribe/Raise an event.
看起来'event'关键字是委托声明的修饰符,允许它包含在接口中,从声明它的类中约束它的调用,为它提供一对可自定义的访问器(添加和删除)并强制委托的签名(在.NET框架中使用时)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.