C#反思程序化事件处理程序与自定义事件精灵 [英] C# Reflection Programmatic Event Handlers with Custom Event Args

查看:93
本文介绍了C#反思程序化事件处理程序与自定义事件精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题/方案

public class TestEventArgs : EventArgs
{
   public int ID { get; set; }
   public string Name { get; set; }
}

public event EventHandler<TestEventArgs> TestClick

如何使用反射将TestHandler附加到TestClick上? (obj是实例,Activator.CreateInstance)

How can I attach an EventHandler on TestClick by using reflection? (obj is instance, Activator.CreateInstance)

EventInfo eventClick = obj.GetType().GetEvent("TestClick");
Delegate handler = Delegate.CreateDelegate(eventClick.EventHandlerType, obj, ????);
eventClick.AddEventHandler(obj, handler);

我的问题是TestEventArgs在外部DLL中声明,上面的methodinfo需要在其委托中签名?

My problem being that TestEventArgs is declared in an external dll, but ???? methodinfo above requires the signature in its delegate?

推荐答案

我设法通过遵循以下描述的技术来使我的代码工作文章,
http: //www.pelennorfields.com/matt/2009/03/13/createdelegate-error-binding-to-target-method/

I manage to get my code to work by following the technique describe by the following article, http://www.pelennorfields.com/matt/2009/03/13/createdelegate-error-binding-to-target-method/

实质上,如果我执行以下操作,我会收到错误,绑定到目标方法的错误,

In essence, if I do the following, I get the error, "Error binding to target method",

失败:

EventInfo eventClick = obj.GetType().GetEvent("TestClick");
Delegate handler = Delegate.CreateDelegate(
    eventClick.EventHandlerType, this, "TestClick");
eventClick.AddEventHandler(obj, handler);

成功:

但是当我更改为:

MethodInfo methodOn_TestClick = this.GetType().GetMethod("TestClick", new Type[] { typeof(object), typeof(EventArgs));

Delegate handler = Delegate.CreateDelegate(
    event_DomClick.EventHandlerType, this, methodOn_TestClick, true); // note the change here

eventClick.AddEventHandler(obj, handler);

然后,我使用TestClick方法中的反射,以获取标准EventArgs中需要的属性。

I then used reflection in my TestClick method, to get the properties I needed out of the standard EventArgs.

例如。

public void TestClick(object sender, EventArgs e)
{
    PropertyInfo prop_ID = e.GetType().GetProperty("ID");

    int id = Convert.toInt32(prop_ID.GetValue(e, null));
}

这篇关于C#反思程序化事件处理程序与自定义事件精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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