windows C# 事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/232863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Event Handlers
提问by Jon Skeet
How can I check in C# if button.Click event has any handlers associated? If (button.Click != null) throws compile error.
如果 button.Click 事件有任何关联的处理程序,我如何检查 C#?如果 (button.Click != null) 抛出编译错误。
回答by Jon Skeet
You can't. Events just expose "add a handler" and "remove a handler" - that's all. (In fact in the CLR you can also have metadata to associate a method with "fire the event" but the C# compiler never generates that.) Some event publishers may offer additional means to check whether or not there are any subscribers (or indeed let you see those subscribers) but it's not part of the event pattern itself.
你不能。事件只是公开“添加处理程序”和“删除处理程序”——仅此而已。(实际上,在 CLR 中,您还可以使用元数据将方法与“触发事件”相关联,但 C# 编译器永远不会生成它。)一些事件发布者可能会提供额外的方法来检查是否有任何订阅者(或者确实让你会看到那些订阅者)但它不是事件模式本身的一部分。
See my article about eventsfor more information, or look at the eventstag (which I'm about to add to this question).
回答by Gishu
Why do you need this? What is the context? Maybe there's a better way to achieve the result
The button is an external object and what you're trying to do is check is its internal list of subscribers without asking it. It's violating encapsulation..
You should always let the object manage the subscribers for the events it exposes. If it wanted clients to be aware, it would have exposed a method HasClientsRegistered. Don't break in.
你为什么需要这个?上下文是什么?也许有更好的方法来实现结果
按钮是一个外部对象,您要做的是检查它的内部订阅者列表而不询问它。它违反了封装。
您应该始终让对象管理它公开的事件的订阅者。如果它想让客户知道,它会公开一个方法 HasClientsRegistered。不要闯进来。
回答by Brody
I think you can if you are in the class that raises the event.
我认为如果你在引发事件的班级,你可以。
You can define the handler and enumerate each.
您可以定义处理程序并枚举每个处理程序。
e.g. If your event is defined as
例如,如果您的事件被定义为
event System.EventHandler NewEvent;
Then on the raise event method you might create you can do...
然后在您可能创建的 raise 事件方法上,您可以执行...
EventHandler handler = NewEvent;
if(handler != null)
{
handler(this, e);
}
That will give you the handler and from that you can get the Invocation List.
这将为您提供处理程序,您可以从中获取调用列表。
回答by incaunu
EventDescriptor e = TypeDescriptor.GetEvents(yourObject).Find("yourEventName", true);
EventDescriptor e = TypeDescriptor.GetEvents(yourObject).Find("yourEventName", true);