我读到这个问题:Overriding Events in VB
It is even an error to override events in C#. The C# Programming Guide says: Do not declare virtual events in a base class and override them in a derived class. The C# compiler does not handle these correctly in Microsoft Visual Studio 2008 and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event. I wonder why a framework class breaks this rule, or even why the compiler allows it.
我不明白为什么覆盖事件是错误的。当然,继承类总是可以监视基类事件并在之后采取自己的行动,但是如果它想确保它是第一个看到该事件的事件观察者怎么办?它想要决定在特定条件下吞下事件的是什么?这样做有什么问题:
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
VerifyActiveCountMatches();
base.OnCollectionChanged(e);
InvokePropertyChanged("Count");
}
最佳答案
这样做不是错误 - 但它很可能是一个糟糕的设计决策。有很大的不同;编译器不会让你逃避错误,但它很少批评你的设计。
您为 OnCollectionChanged
显示的代码不会覆盖事件 - 它覆盖引发事件的方法。那是完全不同的事情。事件类似于:
// "Field-like" event - the compiler implements the add/remove and
// creates a backing field.
public event EventHandler Click;
或
// Manually-implemented event; you write the add/remove yourself, and
// create a separate backing variable if necessary.
public event EventHandler Click
{
add { ... }
remove { ... }
}
这些是处理订阅和取消订阅的代码片段 - 正是这些建议说你不应该覆盖。您很少想要这样做,正如引用的文字所说,在很多情况下它无论如何都不会按照您的意愿去做。
关于c# - 在 C# 中覆盖事件真的会出错吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7679670/