[英]Why can't I get the event handler of a LinkButton's event using reflection?
I want to access the event handler of a LinkButton
's Command
event, but in the snippet bellow fieldInfo
is null. 我想访问
LinkButton
的Command
事件的事件处理程序,但是在下面的代码段中, fieldInfo
为null。
LinkButton button = new LinkButton();
button.Command += (s, e) => { };
Type type = button.GetType();
EventInfo[] eventInfos = type.GetEvents(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (EventInfo eventInfo in eventInfos)
if (eventInfo.Name == "Command")
{
// fieldInfo is null
FieldInfo fieldInfo = eventInfo.DeclaringType.GetField(eventInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
Delegate delegates = (Delegate)fieldInfo.GetValue(button);
foreach (Delegate handler in delegates.GetInvocationList())
{
eventInfo.RemoveEventHandler(button, handler);
// or
eventInfo.AddEventHandler(button, handler);
// or do whatever with handler
}
}
Code snippet was inspired from this . 代码段的灵感来自于此 。
Why is fieldInfo
null ? 为什么
fieldInfo
null?
Is there another way to get the event handler of a LinkButton
's Command
event ? 还有另一种方法来获取
LinkButton
的Command
事件的事件处理程序吗?
Also Hans Passant sollution does not work on LinkButton
using Command
as the field name. 同样,使用
Command
作为字段名称的Hans Passant解决方案在LinkButton
上不起作用。
Looking at the LinkCommand
reference source : 看一下
LinkCommand
参考源 :
public event CommandEventHandler Command
is "magic". public event CommandEventHandler Command
是“魔术”的。
LinkCommand
uses the baseclass UI.Control
and the events are stored in a protected EventHandlerList Events
. LinkCommand
使用基类UI.Control
,并将事件存储在protected EventHandlerList Events
。
LinkCommand
also has a private property called EventCommand
, which appears to be used as the indexer for the Events
list. LinkCommand
还具有一个称为EventCommand
的私有属性,该属性似乎用作“ Events
列表的索引器。
If I'm reading the source correctly, you'll need to extract Events[EventCommand]
and cast it to CommandEventHandler
like LinkButton
does in OnCommand
. 如果我正确地阅读了源代码,则需要提取
Events[EventCommand]
并将其转换为CommandEventHandler
就像LinkButton
在OnCommand
。
This also appears to be a common practice for classes using UI.Control
as a base class. 对于使用
UI.Control
作为基类的类,这似乎也很常见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.