开发者

Overriding Events in VB

开发者 https://www.devze.com 2022-12-20 10:40 出处:网络
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.

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);
            }开发者_如何学运维
        }
    }

}


Rewrite Edit:

A conversation that figures it's a compiler implementation snafu and suggests workarounds:

http://social.msdn.microsoft.com/Forums/en/vblanguage/thread/ce30ceed-c260-4d99-b96d-5b7179466be8

This is my (semi) final answer.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消