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 ?
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.
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.
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.
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.
Use Type.GetEvents(), not GetFields(). You can then use EventInfo.AddEventHandler().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With