“委托减法有不可预知的结果"在 ReSharper/C# 中?

quot;Delegate subtraction has unpredictable resultquot; in ReSharper/C#?(“委托减法有不可预知的结果在 ReSharper/C# 中?)
本文介绍了“委托减法有不可预知的结果"在 ReSharper/C# 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 myDelegate -= eventHandler ReSharper(版本 6)时出现问题:

When using myDelegate -= eventHandler ReSharper (version 6) issues:

委托减法有不可预知的结果

Delegate subtraction has unpredictable result

这背后的原因是 JetBrains 在这里解释.这个解释是有道理的,读完之后,我怀疑我对代表的所有 - 使用.

The rational behind this is explained by JetBrains here. The explanation makes sense and, after reading it, I'm doubting all my uses of - on delegates.

那么

  • 我可以编写一个非自动事件而不让 ReSharper 脾气暴躁吗?
  • 或者,是否有更好和/或正确"的方式来实现这一点?
  • 或者,我可以忽略 ReSharper 吗?

这里是简化的代码:

public delegate void MyHandler (object sender);

MyHandler _myEvent;

public event MyHandler MyEvent
{
    add
    {
        _myEvent += value;
        DoSomethingElse();
    }
    remove
    {
        _myEvent -= value; // <-- ReSharper warning here
    }
}

推荐答案

别怕!ReSharper 警告的第一部分仅适用于删除代表列表.在您的代码中,您总是删除一个委托.第二部分讨论了删除重复代表后代表的顺序.事件并不能保证其订阅者的执行顺序,因此它也不会真正影响您.

Don't be afraid! The first part of ReSharper's warning only applies to removing lists of delegates. In your code, you're always removing a single delegate. The second part talks about ordering of delegates after a duplicate delegate was removed. An event doesn't guarantee an order of execution for its subscribers, so it doesn't really affect you either.

由于上述机制可能导致不可预知的结果,ReSharper 在遇到委托减法运算符时会发出警告.

Since the above mechanics can lead to unpredictable results, ReSharper issues a warning whenever it encounters a delegate subtraction operator.

ReSharper 发出此警告是因为多播委托减法可能存在问题,它并不完全谴责该语言功能.幸运的是,这些陷阱存在于边缘案例中,如果您只是检测简单事件,则不太可能遇到它们.没有更好的方法来实现您自己的 add/remove 处理程序,您只需要注意.

ReSharper is issuing this warning because multicast delegate subtraction can have gotchas, it isn't condemning that language feature entirely. Luckily those gotchas are in fringe cases and you are unlikely to encounter them if you're just instrumenting simple events. There is no better way to implement your own add/remove handlers, you just gotta take notice.

我建议将该消息的 ReSharper 警告级别降级为提示",这样您就不会对他们的警告不敏感,这通常很有用.

I'd suggest downgrading ReSharper's warning level for that message to "Hint" so that you don't get desensitized to their warnings, which are usually useful.

这篇关于“委托减法有不可预知的结果"在 ReSharper/C# 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)