本文介绍了使用反射的 AddEventHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码不起作用:
I have this piece of code that does not work:
public CartaoCidadao()
{
InitializeComponent();
object o = WebDAV.Classes.SCWatcher.LoadAssembly();
MethodInfo method =
this.GetType().GetMethod("Inserted",
BindingFlags.NonPublic | BindingFlags.Instance);
EventInfo eventInfo = o.GetType().GetEvent("CardInserted");
Type type = eventInfo.EventHandlerType;
Delegate handler = Delegate.CreateDelegate(type, this , method);
eventInfo.AddEventHandler(o, handler);
}
void Inserted(string readerName, string cardName)
{
System.Windows.Forms.MessageBox.Show(readerName);
}
事件 CardInserted 存在于另一个 DLL 文件中,并且对象o"加载正常.委托处理程序在效果后有一个值.我只是无法触发事件.
The Event CardInserted exists in another DLL file and object "o" loads OK. The delegate handler has a value after effect. I only can't fire the event.
推荐答案
以下示例展示了如何使用反射附加事件:
Here's a sample showing how to attach an event using reflection:
class Program
{
static void Main(string[] args)
{
var p = new Program();
var eventInfo = p.GetType().GetEvent("TestEvent");
var methodInfo = p.GetType().GetMethod("TestMethod");
Delegate handler =
Delegate.CreateDelegate(eventInfo.EventHandlerType,
p,
methodInfo);
eventInfo.AddEventHandler(p, handler);
p.Test();
}
public event Func<string> TestEvent;
public string TestMethod()
{
return "Hello World";
}
public void Test()
{
if (TestEvent != null)
{
Console.WriteLine(TestEvent());
}
}
}
这篇关于使用反射的 AddEventHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!