开发者

Casting and Types Question

I am bubbling events in my application and so therefore using the bubble events method. As this method handles all sorts of bubbled events their is a switch or if statement within it to determine what sort of event we're dealing with. I was wondering if I could get around this by creating different versions of the event args class. So let me explain, say I have two types of event that are handled differently called X and Y, I create new event args classes for these two events as they store different types of info.

public class EventsArgsX : EventsArgs

public class EventsArgsY : EventsArgs

then when I RaiseBubbleEvent from somewhere in my application I can pass either of the two event arg based types, so..

EventArgsX foox = new EventArgsX();
RaiseBubbleEvent(null,foox);

or

EventArgsY fooy = new EventArgsY();
RaiseBubbleEv开发者_如何转开发ent(null,fooy);

then the OnBubbleEvent method picks this up, who's signature is override OnBubbleEvent(object source, EventArgs e)

now i cant overload this method as its overriden in the first place, so what I thought I could do was have another method with overloads in it to handle this, so

protected override OnBubbleEvent(object source, EventArgs e)
{
    DoStuff(e);
}

private void DoStuff(EventArgsY args)
{}

private void DoStuff(EventArgsX args)
{}

but of course the problem is that EventArgs e in the OnBubbleEvent method is of type EventArgs at the time of calling. However we know its not. So how would i case it back to its actual type in order for the method call to work?

Many thanks, hope you can help me with this, its seems really easy like a might be missing something or that it just cant be done

any ideas??


It's simple:

protected override OnBubbleEvent(object source, EventArgs e)
{
    if(e is EventArgsX)
        DoStuff((EventArgsX)e);
    else if(e is EventArgsY)
        DoStuff((EventArgsY)e);
}

This, being KISS, is not very extensible. If you're planning on adding more event types, you can try double dispatch:

public abstract class EventArgsBase : EventArgs
{
    public abstract void Bubble(IEventBubbler eb);        
}

public interface IEventBubbler
{
    Bubble(EventArgsX ex);

    Bubble(EventArgsY ey);
}

public class EventArgsX : EventArgsBase
{
    public virtual void Bubble(IEventBubbler eb)
    {
        eb.Bubble(this);
    }
}

public class EventArgsY : EventArgsBase
{
    public virtual void Bubble(IEventBubbler eb)
    {
        eb.Bubble(this);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜