如何从一个EventInfo委托对象? [英] How to get a delegate object from an EventInfo?

查看:153
本文介绍了如何从一个EventInfo委托对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从当前类的所有事件,并找出订阅它的方法。 <一href="http://stackoverflow.com/questions/3781963/how-can-i-retrieve-all-methods-of-an-event/3781978#3781978">Here我上如何做到这一点一些答案​​,但我不知道我能获得代理当所有我已经是 EventInfo

I need to get all events from the current class, and find out the methods that subscribe to it. Here I got some answers on how to do that, but I don't know how I can get the delegate when all I have is the EventInfo.

var events = GetType().GetEvents();

foreach (var e in events)
{
    Delegate d = e./*GetDelegateFromThisEventInfo()*/;
    var methods = d.GetInvocationList();
}

是否有可能得到一个代理的 EventInfo ?怎么样?

推荐答案

语句 VAR事件=的GetType()GetEvents(); 让你的列表 EventInfo 与当前的类型,而不是当前实例本身相关联的对象。因此, EventInfo 对象不包含有关当前实例的信息,因此它不知道有线式的代表。

The statement var events = GetType().GetEvents(); gets you a list of EventInfo objects associated with the current type, not the current instance per se. So the EventInfo object doesn't contain information about the current instance and hence it doesn't know about the wired-up delegates.

要得到你想要的,你需要得到支持字段为您的当前实例的事件处理程序的信息。具体方法如下:

To get the info you want you need to get the backing field for the event handler on your current instance. Here's how:

public class MyClass
{
    public event EventHandler MyEvent;

    public IEnumerable<MethodInfo> GetSubscribedMethods()
    {
        Func<EventInfo, FieldInfo> ei2fi =
            ei => this.GetType().GetField(ei.Name,
                BindingFlags.NonPublic |
                BindingFlags.Instance |
                BindingFlags.GetField);

        return from eventInfo in this.GetType().GetEvents()
               let eventFieldInfo = ei2fi(eventInfo)
               let eventFieldValue =
                   (System.Delegate)eventFieldInfo.GetValue(this)
               from subscribedDelegate in eventFieldValue.GetInvocationList()
               select subscribedDelegate.Method;
    }
}

所以,现在您的通话code可以是这样的:

So now your calling code can look like this:

class GetSubscribedMethodsExample
{
    public static void Execute()
    {
        var instance = new MyClass();
        instance.MyEvent += new EventHandler(MyHandler);
        instance.MyEvent += (s, e) => { };

        instance.GetSubscribedMethods()
            .Run(h => Console.WriteLine(h.Name));
    }

    static void MyHandler(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }
}

从上面的输出是:

The output from the above is:

MyHandler
<Execute>b__0

我敢肯定,你可以用code治具左右,如果你想返回的委托,而不是方法的信息,等等。

I'm sure you can jig around with the code if you wish to return the delegate rather than the method info, etc.

我希望这有助于。

这篇关于如何从一个EventInfo委托对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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