如何使用反射从事件中获取基础代理的列表?

rye*_*guy 7 c# reflection

首先,GetInvocationList()不会起作用,因为我希望能够从课外到达他们.我认为它可以用一些反射魔法,这就是我想要弄清楚的.

这就是我现在所拥有的:

fooEventDispatcher.GetType().GetField("FooEvent", BindingFlags.Instance | BindingFlags.NonPublic);
var field = fieldInfo.GetValue(fooEventDispatcher);
Run Code Online (Sandbox Code Playgroud)

我只是不知道该怎么做field.有任何想法吗?

Bro*_*ass 10

这应该工作:

var fieldInfo = fooEventDispatcher.GetType().GetField(
                "FooEvent", BindingFlags.Instance | BindingFlags.NonPublic);
var eventDelegate = fieldInfo.GetValue(fooEventDispatcher) as MulticastDelegate;
if (eventDelegate != null) // will be null if no subscribed event consumers
{
   var delegates = eventDelegate.GetInvocationList();
}
Run Code Online (Sandbox Code Playgroud)

你也应该使用typeof(SomeFooClass)而不是fooEventDispatcher.GetType()在编译时已知类型(我认为它是).

  • 第4行应该是`MulticastDelegate eventDelegate =(MulticastDelegate)字段;` (4认同)