在派生类中提升基类事件C# [英] Raise Base Class Events in Derived Classes C#

查看:153
本文介绍了在派生类中提升基类事件C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类DockedToolWindow:Form,以及从DockedToolWindow派生的许多类。我有一个容器类,它将事件保存并分配给DockedToolWindow对象,但是我想从子类中调用事件。



我实际上有一个关于如何实现的问题这个 MSDN网站正在告诉我这样做。以下这一节给我的问题:

  //事件。请注意,通过使用通用的EventHandler< T>事件类型
//我们不需要声明一个单独的委托类型。
public event EventHandler< ShapeEventArgs> ShapeChanged;

public abstract void Draw();

//派生类的事件调用方法可以覆盖。
protected virtual void OnShapeChanged(ShapeEventArgs e)
{
//创建事件的临时副本,以避免
//竞争条件的可能性,如果最后一个订阅者取消订阅
//在空检查之后和事件发生之前。
EventHandler< ShapeEventArgs> handler = ShapeChanged;
if(handler!= null)
{
handler(this,e);
}
}

确定这个例子编译和工作,但是当我更换ShapeChanged与Move(从Form获取的事件),错误说我不能没有+ =或 - =的右侧的Move。我也删除了ShapeEventArgs通用标签。



任何煽动为什么这不工作?在类中声明的事件与继承的事件有什么区别?

解决方案

您不能直接触发基类事件。这就是为什么你必须使你的 OnShapeChanged 方法保护而不是 private



使用 base.OnMove()


I have a base class DockedToolWindow : Form, and many classes that derive from DockedToolWindow. I have a container class that holds and assigns events to DockedToolWindow objects, however I want to invoke the events from the child class.

I actually have a question about how to implement what this MSDN site is telling me to do. This section below is giving me the problem:

    // The event. Note that by using the generic EventHandler<T> event type
    // we do not need to declare a separate delegate type.
    public event EventHandler<ShapeEventArgs> ShapeChanged;

    public abstract void Draw();

    //The event-invoking method that derived classes can override.
    protected virtual void OnShapeChanged(ShapeEventArgs e)
    {
        // Make a temporary copy of the event to avoid possibility of
        // a race condition if the last subscriber unsubscribes
        // immediately after the null check and before the event is raised.
        EventHandler<ShapeEventArgs> handler = ShapeChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }

Sure this example compiles and works, but when I replace "ShapeChanged" with "Move" (an event I acquired from deriving from Form), it errors saying I cannot have Move on the right side without += or -=. I also removed the ShapeEventArgs generic tags.

Any incite on why this isn't working? What's the difference between an event declared within the class and one that is inherited?

解决方案

You cannot directly fire base class events. This is exactly the reason why you had to make your OnShapeChanged method protected instead of private.

Use base.OnMove() instead.

这篇关于在派生类中提升基类事件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆