委托和事件
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event
委托
委托可以理解为函数指针,也可以简单理解为一类相似的方法的引用
调用委托时可以直接用c++指针的写法,也可用.invoke的写法
委托和世界经常被用来简化冗余代码,降低代码耦合性
delegate int NumberChanger(int a,int b);
public static int AddNum(int a,int b)
{
num += p;
return num;
}
//创建委托示例
NumberChanger nc=new NumberChanger(AddNum)
//使用委托
int a=2,b=3;
int res = nc(2,3)
//等价写法 : int res = nc.invoke(2,3);
事件
事件是特殊的一种多播委托(但是和委托用法有区别):
Events are a special kind of multicast delegate that can only be invoked from within the class or struct where they are declared (the publisher class). If other classes or structs subscribe to the event, their event handler methods will be called when the publisher class raises the event.
Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.
事件是被声明在类中的
声明事件(在Publisher class中):
public class Publisher
{
// Declare the delegate (if using non-generic pattern).先声明委托SampleEventHandler
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
// Declare the event. 再声明事件
public event SampleEventHandler SampleEvent;
// Wrap the event in a protected virtual method
// to enable derived classes to raise the event.事件发生,发送参数
protected virtual void RaiseSampleEvent()
{
// Raise the event in a thread-safe manner using the ?. operator.
SampleEvent?.Invoke(this, new SampleEventArgs("Hello"));
}
}
//这个是事件消息的参数 class SampleEventArgs
public class SampleEventArgs
{
public SampleEventArgs(string text) { Text = text; }
public string Text { get; } // readonly
}
事件处理器EventHandler,这个就是处理事件的方法,也可以当做回调函数使用
这个方法必须和publisher中委托约定参数类型和返回类型相匹配才能被订阅
void HandleCustomEvent(object sender, CustomEventArgs a)
{
// Do something useful here.
}
订阅/取消事件:用+=或者-=,不能用=
publisher.RaiseCustomEvent += HandleCustomEvent;