如何知道引发了哪个事件

时间:2014-02-04 13:38:22

标签: c# events delegates event-handling

例如,请考虑以下类:

public class Test
{
    public event EventHandler<EventArgs> BeforeLayoutRendering;
    public event EventHandler<EventArgs> BeforeItemRendering;
    public event EventHandler<EventArgs> AfterLayoutRendering;
    public event EventHandler<EventArgs> AfterItemRendering;
}

public class Monitor
{
    public Monitor(Test objBeingMonitored)
    {
        objBeingMonitored.BeforeLayoutRendering += Before;
        objBeingMonitored.BeforeItemRendering += Before;
        objBeingMonitored.AfterLayoutRendering += After;
        objBeingMonitored.AfterItemRendering += After;
    }

    public void Before(object sender, EventArgs e)
    {
        // Which event was raised?
    }

    public void After(object sender, EventArgs e)
    {
        // Which event was raised?
    }
}

如果我对多个事件使用相同的处理程序,我怎么知道引发了哪个事件?我知道我可以改变我在EventHandler中使用的TEventArgs类,我只是想知道框架是否有内置的东西。

1 个答案:

答案 0 :(得分:3)

以下是一种了解方法:

public class Monitor
{
    internal enum eEvent: byte { Layout, Item }

    public Monitor( Test objBeingMonitored )
    {
        objBeingMonitored.BeforeLayoutRendering += ( s, e ) => Before( eEvent.Layout, s, e );
        objBeingMonitored.BeforeItemRendering += ( s, e ) => Before( eEvent.Item, s, e );
        objBeingMonitored.AfterLayoutRendering += ( s, e ) => After( eEvent.Layout, s, e );
        objBeingMonitored.AfterItemRendering += ( s, e ) => After( eEvent.Item, s, e );
    }

    internal void Before( eEvent evt, object sender, EventArgs e ) { }
    internal void After( eEvent evt, object sender, EventArgs e ) { }
}