使用反射添加事件处理程序?/获取类型的对象? [英] Add Event Handler using Reflection ? / Get object of type?
问题描述
如果我只有事件抛出者的类型 AType
,如何使用反射添加事件处理程序 myhandler
?
how to add a event handler myhandler
using reflection if I only have the type AType
of the event thrower?
Delegate myhandler = SomeHandler;
EventInfo info= AType.GetEvent("CollectionChanged");
info.AddEventHandler( ObjectOfAType, myhandler )
推荐答案
基本上,您所拥有的都很好.唯一的问题是 myhandler
实际上必须是正确的类型,也就是说:事件定义的类型.
Basically, what you have is fine. The only glitch is that myhandler
actually needs to be of the correct type, which is to say: of the type defined by the event.
例如:
using System;
using System.Collections.Specialized;
using System.Reflection;
class Program
{
static void Main()
{
Type AType = typeof(Foo);
var ObjectOfAType = new Foo();
Delegate myhandler = (NotifyCollectionChangedEventHandler)SomeHandler;
EventInfo info = AType.GetEvent("CollectionChanged");
info.AddEventHandler(ObjectOfAType, myhandler);
// prove it works
ObjectOfAType.OnCollectionChanged();
}
private static void SomeHandler(object sender, NotifyCollectionChangedEventArgs e)
=> Console.WriteLine("Handler invoked");
}
public class Foo
{
public void OnCollectionChanged() => CollectionChanged?.Invoke(this, null);
public event NotifyCollectionChangedEventHandler CollectionChanged;
}
有一个 Delegate.CreateDelegate()
方法,该方法带有一个委托类型,一个对象实例和一个 MethodInfo
方法;您可以使用它(使用 EventInfo info
中的事件类型)为特定对象上的给定方法创建适当的委托实例.
There is a Delegate.CreateDelegate()
method that takes a delegate type, an object instance, and a MethodInfo
method; you can use this (using the event-type from EventInfo info
) to create an appropriate delegate instance for a given method on a particular object.
这篇关于使用反射添加事件处理程序?/获取类型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!