zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#中事件的动态调用实现方法

c#事件方法 实现 动态 调用
2023-06-13 09:15:45 时间

本文实例讲述了C#动态调用事件的方法。一般来说,传统的思路是,通过Reflection.EventInfo获得事件的信息,然后使用GetRaiseMethod方法获得事件被触发后调用的方法,再使用MethodInfo.Invoke来调用以实现事件的动态调用。

但是很不幸的,Reflection.EventInfo.GetRaiseMethod方法始终返回null。这是因为,C#编译器在编译并处理由event关键字定义的事件时,根本不会去产生有关RaiseMethod的元数据信息,因此GetRaiseMethod根本无法获得事件触发后的处理方法。ThottamR.Sriram在其UsingSetRaiseMethodandGetRaiseMethodandinvokingthemethoddynamically一文中简要介绍了这个问题,并通过Reflection.Emit相关的方法来手动生成RaiseMethod,最后使用常规的GetRaiseMethod来实现事件触发后的方法调用。这种做法比较繁杂。

以下代码是一个简单的替代方案,同样可以实现事件的动态调用。具体代码如下:

publiceventEventHandler<EventArgs>MyEventToBeFired;
publicvoidFireEvent(GuidinstanceId,stringhandler)
{
//Note:thisisbeingfiredfromamethodwithinthesameclassthatdefinedtheevent(i.e."this").
EventArgse=newEventArgs(instanceId);
MulticastDelegateeventDelagate=(MulticastDelegate)this
.GetType()
.GetField(handler,BindingFlags.Instance|BindingFlags.NonPublic)
.GetValue(this);
Delegate[]delegates=eventDelagate.GetInvocationList();
foreach(Delegatedlgindelegates)
{
dlg.Method.Invoke(dlg.Target,newobject[]{this,e});
}
}
FireEvent(newGuid(),"MyEventToBeFired");

希望本文所述对大家的C#程序设计有所帮助