如何调用方法获取事件名称 [英] How to get event name in called method

查看:450
本文介绍了如何调用方法获取事件名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用反射来的事件处理程序添加到一个事件:

I am using reflection to add an event handler to an event :

var eventInfo = type.GetEvent(eventName);
MethodInfo mi = GetType().GetMethod("TestMethod", 
           BindingFlags.Instance | BindingFlags.NonPublic);
var delegateForMethod = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, mi);
eventInfo.AddEventHandler(this, delegateForMethod);

这成功地调用事件发生时,这是伟大的我的测试方法,但现在我需要知道这结束了调用这个方法的事件的名称...

This successfully calls my test method when the event occurs which is great, but now I need to know the name of the event that ended up calling this method...

void TestMethod(object sender, EventArgs e)
{
    // I know the sender, but which event was fired on the sender?
}



我需要这样做的原因是因为我有勾搭这个通用寄存器方法处理程序不同的类型,以及不同的事件和信道所有这些一种方法,同时也使纸币的什么附着。一旦测试方法火灾,我要拉出来了说明和使用信息通知正确的对象,他们的预期事件已经被解雇。 - 但要知道这一点,我需要知道事件的名称以及类型

The reason I need this is because I have this generic register method which hooks up handlers to different types, and different events and channels them all to one method, while also making a note of what was attached. Once the test method fires, I need to pull out that note and use the info to notify the correct object that their "desired" event has fired. -- but to know this I need to know the event name as well as the type.

例如,在寄存器我添加事件A的X型对象O. ...现在,当我看到它的测试方法引发的,我需要知道它是事件A的X型,这样我就可以通过一定的接口方法就可以了通知对象O操作。

For example, in register I added Event A in type X for object O.... now when I see it triggered in the test method, I need to know it was Event A in type X, so I can notify object O by a certain interface method on it.

推荐答案

有没有那个canot通过引入抽象出新的水平来解决问题!

There is no problem that canot be solved by introducing an additional level of abstraction!

像这样绑定事件

obj.SomeEvent += (sender, args) => TestMethod("SomeEvent", sender, args);

或反射:

var eventInfo = type.GetEvent(eventName);
EventHandler delegateForMethod = (o, args) => TestMethod(eventInfo.Name, o, args);
eventInfo.AddEventHandler(this, delegateForMethod);

和在处理程序可以从参数访问事件名称:

And in handler you can access event name from parameter:

void TestMethod(string eventName, object sender, EventArgs e)
{
    // eventName is event was fired on the sender
    TestMethod(sender, e);
}

这篇关于如何调用方法获取事件名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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