更新时间:2023-01-23 17:54:02
它甚至覆盖在C#中的事件错误。该 C#编程指南说:
不要声明在
基类的虚拟事件,并在
派生类中覆盖它们。 C#编译器不会
不是在
微软Visual Studio 2008中正确处理这些,这是
不可预知的订户
派生事件是否实际上是
订阅了基类的事件。
块引用>我不知道为什么一个框架类打破了这种规则,甚至是编译器为什么允许它。
Is there a way to translate this code in VB? Most of it is easy, but I can't figure out a way to override the event handler.
public class MTObservableCollection<T> : ObservableCollection<T> { public MTObservableCollection() { _DispatcherPriority = DispatcherPriority.DataBind; } public MTObservableCollection(DispatcherPriority dispatcherPriority) { _DispatcherPriority = dispatcherPriority; } private DispatcherPriority _DispatcherPriority; public override event NotifyCollectionChangedEventHandler CollectionChanged; protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { var eh = CollectionChanged; if (eh != null) { Dispatcher dispatcher = (from NotifyCollectionChangedEventHandler nh in eh.GetInvocationList() let dpo = nh.Target as DispatcherObject where dpo != null select dpo.Dispatcher).FirstOrDefault(); if (dispatcher != null && dispatcher.CheckAccess() == false) { dispatcher.Invoke(DispatcherPriority.DataBind, (Action)(() => OnCollectionChanged(e))); } else { foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList()) nh.Invoke(this, e); } } } }
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.