如何使用反射从事件中获取底层委托的列表? [英] How can I get a list of the underlying delegates from an event using reflection?

查看:36
本文介绍了如何使用反射从事件中获取底层委托的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,GetInvocationList() 不起作用,因为我希望能够从课外访问它们.我假设它与一些反射魔法一起工作,这就是我想要弄清楚的.

First, GetInvocationList() won't work, because I want to be able to get to them from outside the class. I assume it will work with some reflection magic, and that's what I'm trying to figure out.

这是我现在拥有的:

fooEventDispatcher.GetType().GetField("FooEvent", BindingFlags.Instance | BindingFlags.NonPublic);
var field = fieldInfo.GetValue(fooEventDispatcher);

我只是不知道如何处理field.有什么想法吗?

I just don't know what to do with field. Any ideas?

推荐答案

这应该有效:

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();
}

此外,如果类型在编译时已知(我假设是),则您应该使用 typeof(SomeFooClass) 而不是 fooEventDispatcher.GetType().

Also you should use typeof(SomeFooClass) instead of fooEventDispatcher.GetType() if the type is already known at compile time (which I assume it is).

这篇关于如何使用反射从事件中获取底层委托的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆