我正在尝试将控件序列化为 XML,并且我想序列化它们的事件处理程序。
我正在使用这段代码:
Control childCtrl = ....
if (childCtrl.GetType() == typeof(Button)) {
EventInfo baseEventInfo = childCtrl.GetType().GetEvent("Click");
EventHandlerList events =
typeof(Control).GetProperty("Events",
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.NonPublic).GetValue(childCtrl, null)
as EventHandlerList;
object eventField = typeof(Control).GetField("Event" + baseEventInfo.Name,
BindingFlags.NonPublic |
BindingFlags.Static).GetValue(childCtrl);
Delegate aDel = events[eventField];
xmlSerialisedForm.WriteElementString("Click", aDel.Method.ToString());
}
if (childCtrl.GetType() == typeof(CheckBox)) {
EventInfo baseEventInfo = childCtrl.GetType().GetEvent("CheckedChanged");
EventHandlerList events =
typeof(Control).GetProperty("Events",
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.NonPublic).GetValue(childCtrl, null)
as EventHandlerList;
//Error here: GetField returns null
object eventField = typeof(Control).GetField("Event" + baseEventInfo.Name,
BindingFlags.NonPublic |
BindingFlags.Static).GetValue(childCtrl);
Delegate aDel = events[eventField];
xmlSerialisedForm.WriteElementString("CheckedChanged", aDel.Method.ToString());
}
现在我知道复选框有一个为事件绑定的处理程序CheckedChanged
;使用调试器时,我可以在以下位置看到该方法EventHandlerList
:
现在,在处理 Button 时(当我想要获取与Click
事件关联的委托时),相同的代码实际上可以工作。为什么它不适用于 CheckBox?我在这里想念什么?
编辑:我从调用和查看数组中GetFields
推断出的当前解决方法(非常丑陋):typeof(CheckBox)
if (childCtrl.GetType() == typeof(CheckBox)) {
EventHandlerList events =
typeof(Control).GetProperty("Events",
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.NonPublic).GetValue(childCtrl, null)
as EventHandlerList;
object eventField =
typeof(CheckBox).GetFields(BindingFlags.NonPublic |
BindingFlags.Static)[0].GetValue(childCtrl);
Delegate aDel = events[eventField];
xmlSerialisedForm.WriteElementString("CheckedChanged", aDel.Method.ToString());
}