对不起,标题不明确。
除了我的先例问题,我想订阅一个方法来动态检索(通过反射)的事件对象。有问题的对象是 Control 的一个字段:
public void SubscribeEvents(Control control)
{
Type controlType = control.GetType();
FieldInfo[] fields = controlType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo method = typeof(Trace).GetMethod("WriteTrace");
// "button1" hardcoded for the sample
FieldInfo f = controlType.GetField("button1", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// "Click" hardcoded for the sample
EventInfo eInfo = f.FieldType.GetEvent("Click");
if (eInfo != null)
{
EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eInfo.Name);
Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);
eInfo.AddEventHandler(?????, realDelegate); // How can I reference the variable button1 ???
}
}
我不知道如何引用变量'button1'。我试过这样的事情:
public void SubscribeEvents(Control control)
{
Type controlType = control.GetType();
FieldInfo[] fields = controlType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo method = typeof(Trace).GetMethod("WriteTrace");
// "button1" hardcoded for the sample
FieldInfo f = controlType.GetField("button1", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// "Click" hardcoded for the sample
EventInfo eInfo = f.FieldType.GetEvent("Click");
Type t = f.FieldType;
object o = Activator.CreateInstance(t);
f.GetValue(o);
if (eInfo != null)
{
EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eInfo.Name);
Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);
eInfo.AddEventHandler(o, realDelegate); // Why can I refer to the variable button1 ???
}
}
但我在这里有一个例外:
f.GetValue(o);
System.ArgumentException 未处理 Message=Field 'button1' 在类型“WindowsFormsApplication1.Form1”上定义不是“System.Windows.Forms.Button”类型的目标对象上的字段。