How to set an event handler dynamically using Refl

2020-07-16 08:36发布

I'd like to dynamically set a list of custom event handlers something like this in pseudo-code:

FieldInfo[] fieldInfos = this.GetType().GetFields(
     BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

foreach (FieldInfo fieldInfo in fieldInfos)
{
    if this.fieldInfo.GetType() = TypeOf(CustomEventHandler<this.fieldInfo.Name>) {
        this.fieldInfo.Name += new CustomEventHandler<this.fieldInfo.Name>(OnChange<this.fieldInfo.Name>);
    }
}

I can't find the right syntax can you ?

2条回答
ら.Afraid
2楼-- · 2020-07-16 08:54

Use Type.GetEvents(), not GetFields(). You can then use EventInfo.AddEventHandler().

查看更多
聊天终结者
3楼-- · 2020-07-16 09:04

How about GetEvents instead of GetFields?

    var t = something.GetType();

    var eventInfos = t.GetEvents();

    foreach (var info in eventInfos)
    {
        if (info.EventHandlerType == TypeOf(CustomEventHandler<this.fieldInfo.Name>)
                info.AddEventHandler(...);                
    }

I'm not totally sure about the type-comparison, but then again, fieldInfo.Name can't be used in a generic like that.

查看更多
登录 后发表回答