我想找出已分配哪些方法来处理控件的事件(从外部),然后分配相同的方法来处理另一个控件的相同事件。我尝试了以下方法但没有成功:
private void ReflectMethods(Control control, Control baseControl, string[] excludedEventNames = null, string[] includedEventNames = null)
{
Type baseType = baseControl.GetType();
Type ownType = control.GetType();
foreach (EventInfo baseEventInfo in baseType.GetEvents())
{
if (excludedEventNames != null && excludedEventNames.Contains(baseEventInfo.Name))
continue;
if (includedEventNames != null && !includedEventNames.Contains(baseEventInfo.Name))
continue;
//
// Checking if current control has the same event..
//
foreach (EventInfo ownEventInfo in ownType.GetEvents())
{
if (ownEventInfo.Name == baseEventInfo.Name)
{
FieldInfo eventField = baseType.GetField(baseEventInfo.Name, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
// The above line always returns null, so I cannot get the handler ???
EventHandler eventHandler = (EventHandler)eventField.GetValue(baseControl);
ownEventInfo.AddEventHandler(this, eventHandler);
}
}
}
}