如何使用reflection从事件中获取基础代理的列表?
首先, GetInvocationList()
不起作用,因为我希望能够从类外部获取它们。 我认为它可以用一些reflection魔法,这就是我想要弄清楚的。
这就是我现在所拥有的:
fooEventDispatcher.GetType().GetField("FooEvent", BindingFlags.Instance | BindingFlags.NonPublic); var field = fieldInfo.GetValue(fooEventDispatcher);
我只是不知道该怎么做field
。 有任何想法吗?
这应该工作:
var fieldInfo = fooEventDispatcher.GetType().GetField( "FooEvent", BindingFlags.Instance | BindingFlags.NonPublic); var field = fieldInfo.GetValue(fooEventDispatcher); MulticastDelegate eventDelegate = (MulticastDelegate)field.GetValue(fooEventDispatcher); if (eventDelegate != null) // will be null if no subscribed event consumers { var delegates = eventDelegate.GetInvocationList(); }
如果类型在编译时已经知道(我假设它是),你也应该使用typeof(SomeFooClass)
而不是fooEventDispatcher.GetType()
)。