【发布时间】:2010-10-21 06:28:40
【问题描述】:
我有一个基类 DockedToolWindow : Form,以及许多从 DockedToolWindow 派生的类。我有一个容器类,它保存并将事件分配给 DockingToolWindow 对象,但是我想从子类调用事件。
我实际上对如何实现MSDN site 告诉我的操作有疑问。下面的这一部分给了我这个问题:
// 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);
}
}
当然,这个示例可以编译并且可以工作,但是当我将“ShapeChanged”替换为“Move”(我从 Form 派生的一个事件)时,它会出错,说如果没有 += 或 -=,我不能在右侧移动 Move。我还删除了 ShapeEventArgs 通用标签。
关于为什么这不起作用的任何煽动?在类中声明的事件和继承的事件有什么区别?
【问题讨论】:
标签: c# events base-class