Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an event handler dynamically using Reflection

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 ?

like image 989
user310291 Avatar asked Jan 29 '11 18:01

user310291


People also ask

What is reflection in C# and how do you implement reflection?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

What is dynamic method C#?

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.

What are event handler methods?

To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you're handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button.


2 Answers

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.

like image 187
Henk Holterman Avatar answered Sep 23 '22 07:09

Henk Holterman


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

like image 34
Hans Passant Avatar answered Sep 24 '22 07:09

Hans Passant