C#.NET 4.0 后期动态触发事件设已有类 EventMain
{
[EventCustomFlagAttribute(Action.Show)]
public Event EventHandler myEvent1;
}注意:事件上会用自定义特性标识,事件名称在实际使用时是未知的目的:
需要在运行时动态的触发该myEvent1事件
事件触发后执行的方法是在运行时绑定的,方法未知我想是通过反射拿到该事件EventInfo
然后触发这个事件?GetRaiseMethod方法什么也拿不到
{
[EventCustomFlagAttribute(Action.Show)]
public Event EventHandler myEvent1;
}注意:事件上会用自定义特性标识,事件名称在实际使用时是未知的目的:
需要在运行时动态的触发该myEvent1事件
事件触发后执行的方法是在运行时绑定的,方法未知我想是通过反射拿到该事件EventInfo
然后触发这个事件?GetRaiseMethod方法什么也拿不到
{
[EventCustomFlagAttribute(Action.Show)]
public Event EventHandler myEvent1; public void FireMyEvent1() //<---
{
EventHandler my = this.myEvent1;
if( my != null ) my(this, EventArgs.Empty);
}
}
我只是通过EventCustomFlagAttribute特性来判断事件类型来触发
获得订阅这个事件的方法后调用这些方法提供一个方法来做是可以,但不是我要解决这个的方法,况且还要协定方法名
{
[EventCustomFlagAttribute(Action.Show)]
public Event EventHandler myEvent1; public void FireMyEvent1() //<---
{
EventHandler my = this.myEvent1;
if( my != null ) my(this, EventArgs.Empty);
}
}
典型的调用事件。
1、"public Event ..."的写法是用来让别人订阅和取消订阅事件的,不是用来让别人触发事件。
强行触发(不论及可行与否)违反了隔离原则。2、理论上类的内部完全可以自定义事件激发过程,甚至可以完全没有真实的事件激发。你从外部如何触发?
[EventCustomFlagAttribute(Action.Show)]
public event EventHandler MyFake
{
add { MessageBox.Show("Welcome"); }
remove { MessageBox.Show("Bye-bye"); }
}
EventMain em = new EventMain();
em.myEvent1 += (sender, e) =>
{
Console.WriteLine("ojlovecd");
}; Type t = typeof(EventMain);
foreach (EventInfo ei in t.GetEvents())
{
object[] attributes = ei.GetCustomAttributes(typeof(EventCustomFlagAttribute), false);
if (attributes.Length == 1)
{
FieldInfo fi = t.GetField(ei.Name, BindingFlags.NonPublic | BindingFlags.Instance);
if (fi != null)
{
Delegate del = fi.GetValue(em) as Delegate;
if (del != null)
del.DynamicInvoke(new object[] { new object(), new EventArgs() });
}
}
}
我实际上是在基类里去做这件事情。EventInfo拿到后就是想办法调用了。对于类内部而已,应该是可以调用这个事件的。
System.Runtime.InteropServices._EventInfo 找到这样一个接口,里面有如下这样一个方法
void Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
但是System.Reflection.EventInfo未实现Invoke,不可直接调用
比如把public Event EventHandler myEvent1放到基类,甚至可以写成virtual或abstract。那是系统给COM交互用的。