1
我想知道哪些方法已被分配來處理控件的事件(來自外部),然後分配相同的方法來處理相同的事件另一種控制。我嘗試了以下方法但沒有成功:如何獲得控制器的處理方法來處理另一個控件的相同事件
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);
}
}
}
}
+1感謝您的富有表現力的解決方案。 – Mimi