使用 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.
那么,
这里是简化的代码:
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# 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!