C# 检查是否已附加特定的事件处理程序方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15238701/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:34:50  来源:igfitidea点击:

Check if a specific event handler method already attached

c#.neteventsc#-4.0event-handling

提问by Shiv

Related to this question, Check if an event already exists

与此问题相关, 检查事件是否已存在

but the difference is I just want to know if a particular method is attached to the event. So there may be othermethods attached, but I just want to know if a particular one exists.

但不同的是我只想知道事件是否附加了特定的方法。所以可能附加了其他方法,但我只想知道是否存在特定的方法。

My environment is C# in dotnet 4.0.

我的环境是 dotnet 4.0 中的 C#。

E.g.

例如

Event += MyMethod1;
Event += MyMethod2;

// Some code
if (MyMethod1IsAttachedToEvent())
{
    // Achieved goal
}

Is this possible?

这可能吗?

采纳答案by Parimal Raj

No. You cannot.

你不能。

The eventkeyword was explicitly invented to prevent you from doing what you want to do. It makes the delegate object for the event inaccessible so nobody can mess with the events handlers.

事件关键字是明确的发明,以防止你做你想做的事。它使事件的委托对象无法访问,因此没有人可以弄乱事件处理程序。

Source : How to dermine if an event is already subscribed

来源:如何确定已订阅事件

回答by TalentTuner

Event.GetInvocationList().Any(x => x.Method.Name.Equals("yourmethodname"));

回答by Benjiman

foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
{
    if ( existingHandler == prospectiveHandler )
    {
          return true;
    }
}

loop through the delegates using the GetInvocationListmethod.

使用该GetInvocationList方法循环遍历委托。