关于event的override
转自:http://www.blogjava.net/bubbletea/archive/2006/02/28/32894.html
很多情况下事件由基类注册,子类引发, 但基类中定义的事件只能由基类引发,于是就有了override event。
using System;
public delegate void Del();
class Base
{
public virtual event Del DelEvent;
}
class Derived:Base
{
public override event Del DelEvent;
public void Fire()
{
if (DelEvent != null)
{
DelEvent();
}
}
}
class Test
{
public void Print()
{
Console.WriteLine("Print");
}
public static void Main()
{
Test t = new Test();
Base b = new Derived();
b.DelEvent += new Del(t.Print);
((Derived)b).Fire();
}
}
public delegate void Del();
class Base
{
public virtual event Del DelEvent;
}
class Derived:Base
{
public override event Del DelEvent;
public void Fire()
{
if (DelEvent != null)
{
DelEvent();
}
}
}
class Test
{
public void Print()
{
Console.WriteLine("Print");
}
public static void Main()
{
Test t = new Test();
Base b = new Derived();
b.DelEvent += new Del(t.Print);
((Derived)b).Fire();
}
}
下面显示错误引发方式:
using System;
public delegate void Del();
class Base
{
public event Del DelEvent;
}
class Derived:Base
{
public void Fire()
{
if (base.DelEvent != null)
{
base.DelEvent();
}
}
}
class Test
{
public void Print()
{
Console.WriteLine("Print");
}
public static void Main()
{
Test t = new Test();
Base b = new Derived();
b.DelEvent += new Del(t.Print);
((Derived)b).Fire();
}
}
public delegate void Del();
class Base
{
public event Del DelEvent;
}
class Derived:Base
{
public void Fire()
{
if (base.DelEvent != null)
{
base.DelEvent();
}
}
}
class Test
{
public void Print()
{
Console.WriteLine("Print");
}
public static void Main()
{
Test t = new Test();
Base b = new Derived();
b.DelEvent += new Del(t.Print);
((Derived)b).Fire();
}
}
也可以避免使用override event,如下:
using System;
public delegate void Del();
class Base
{
public event Del DelEvent;
protected void FireEvent()
{
if (DelEvent != null)
{
DelEvent();
}
}
}
class Derived:Base
{
public void Fire()
{
base.FireEvent();
}
}
class Test
{
public void Print()
{
Console.WriteLine("Print");
}
public static void Main()
{
Test t = new Test();
Base b = new Derived();
b.DelEvent += new Del(t.Print);
((Derived)b).Fire();
}
}
public delegate void Del();
class Base
{
public event Del DelEvent;
protected void FireEvent()
{
if (DelEvent != null)
{
DelEvent();
}
}
}
class Derived:Base
{
public void Fire()
{
base.FireEvent();
}
}
class Test
{
public void Print()
{
Console.WriteLine("Print");
}
public static void Main()
{
Test t = new Test();
Base b = new Derived();
b.DelEvent += new Del(t.Print);
((Derived)b).Fire();
}
}