我怎样才能得到使用反射事件的根本代表的名单? [英] How can I get a list of the underlying delegates from an event using reflection?

查看:115
本文介绍了我怎样才能得到使用反射事件的根本代表的名单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先, 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.

这就是我现在所拥有的:

Here's what I have right now:

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



我只是不知道如何处理字段做。 ?任何想法

推荐答案

这应该工作:

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(),如果该类型在编译时已经知道(我假设它是)。

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天全站免登陆