考虑下面的场景,可能这个场景是非常假设的
public delegate void MyDel();
public class T1
{
public T1()
{
}
public virtual event MyDel MyEvent;
public virtual void RaiseEvent()
{
MyEvent();
}
protected virtual void HandleEvent()
{
MessageBox.Show("base event");
}
}
public class T2:T1
{
public override event MyDel MyEvent;
public T2()
{
MyEvent += new MyDel(HandleEvent);
}
protected override void HandleEvent()
{
MessageBox.Show("overridden event");
}
}
和主要客户代码
baseT = new T2();
baseT.MyEvent += new MyDel(() => MessageBox.Show("From client"));
baseT.RaiseEvent();
为什么它会抛出异常,为什么虚拟事件的行为不像虚拟/覆盖方法?