c# - 在 C# 中覆盖事件真的会出错吗?

标签 c# wpf .net-3.5 coding-style event-handling

我读到这个问题: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/

相关文章:

c# - 如何使用 LINQ 将字典值的 SUM 嵌套到列表中?

wpf - 绑定(bind)到附加属性不起作用

c# - .NET Framework 3.5 的等效元组 (.NET 4)

unit-testing - 为什么在测试DateTime相等性时此单元测试失败?

c# - ListView.RetrieveVirtualItem 事件到底是什么 - C#

C# 将相同的变量传递给两个 "out"参数

c# - 如何使动画的持续时间动态化?

c# - 是否可以有效使用更改音频 (mp3) 文件的哈希值

c# - 在 Wpf 中使用 Color.GetSaturation、Color.GetBrightness

wpf - 在开始拖动之前,ListView丢失选择