How to set an event handler dynamically using Refl

2020-07-16 08:56发布

问题:

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 ?

回答1:

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.



回答2:

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