Event triggered by event on base class, not derived class
I have the following structure:
class item
Static EventHandler Boom
public virtual void handleStuff();
public void DoStuff()
trigger Boom EventHandler
handleStuff();
class childItem1 : item
override handleStuff() etc
class childItem2 : item
override handleStuff() etc
So basicly when I call childItem1.DoStuff(); it will trigger the even on the "Item" class and then execute the 开发者_Python百科handleStuff() on the childItem1 class.
So here's my problem, when I subscribe to the event childItem1.Boom it will also trigger if I call childITem2.Dostuff(); as it also triggers the boom event on the "item" class
So here's the question, how can I defined eventhandlers on a base class, which I can subscribe to on derived classes, but without the above issue?
This must be because you have your event declared as Static
.
If you have an non-static event declared on your base class then the event will be invoked correctly as you expect.
The following program will print Derived
apprpriately -
class Program
{
static void Main(string[] args)
{
var d = new Derived();
d.Boom += new EventHandler(HandleBoom);
d.TriggerBoom();
Console.ReadLine();
}
static void HandleBoom(object sender, EventArgs e)
{
Console.WriteLine(sender.GetType());
}
}
class Base
{
public event EventHandler Boom = null;
public void TriggerBoom()
{
if(Boom != null)
Boom(this, EventArgs.Empty);
}
}
class Derived : Base
{
}
精彩评论