我有这段代码不起作用:
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”加载正常。委托(delegate)处理程序具有一个后效值。我只能解雇该 Activity 。
最佳答案
这是显示如何使用反射附加事件的示例:
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());
}
}
}
关于c# - 使用反射的AddEventHandler,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1121441/