每个事件是否由相同的委托类型构成,是否拥有自己的多播委托?

时间:2015-01-23 09:00:26

标签: c# events delegates

如果我有类似的话:

    static class Program
{
    public static delegate void TestHandler();
    public static event TestHandler TestEvent;
    public static event TestHandler TestEvent1;
    public static event TestHandler TestEvent2;


    static void Main(string[] args)
    {

        TestEvent += DoSomething1;
        TestEvent1 += DoSomething2;
        TestEvent2 += DoSomething3;

        Trigger();

        Console.ReadLine();
    }

    public static void Trigger()
    {
        TestEvent();
        TestEvent1();
        TestEvent2();
    }


    private static void DoSomething3()
    {
        Console.WriteLine("Something 3 was done");
    }

    private static void DoSomething2()
    {
        Console.WriteLine("Something 2 was done");
    }

    private static void DoSomething1()
    {
        Console.WriteLine("Something 1 was done");
    }

每个事件是否都是相同类型,是否拥有自己的多播委托?如何为同一个委托类型的每个事件分隔调用列表?

2 个答案:

答案 0 :(得分:1)

Delegates实际上是类。因此,在您的情况下,为TestHandler委托创建了一种类型。该类有三种不同的实例。

您可以在生成的IL代码中轻松看到这一点:

enter image description here

正如您所看到的那样,有TestHandler类型,并且该类型有三个字段。所以它们共享相同的类型,但它们是完全分开的......

答案 1 :(得分:1)

是的,每个event都有自己的多播委托支持字段。事件类型(因此字段类型)相同,不会改变它。

代码:

public delegate void TestHandler();

static class Program
{
    public static event TestHandler TestEvent;
    public static event TestHandler TestEvent1;
    public static event TestHandler TestEvent2;
}

或多或少意味着:

public delegate void TestHandler();

static class Program
{
    // backing fields with the same names:
    private static TestHandler TestEvent;
    private static TestHandler TestEvent1;
    private static TestHandler TestEvent2;

    // each event is really a pair of two "methods" (accessors)
    public static event TestHandler TestEvent
    {
        add
        {
            // smart code to access the private field in a safe way,
            // combining parameter 'value' into that
        }
        remove
        {
            // smart code to access the private field in a safe way,
            // taking out parameter 'value' from that
        }
    }
    public static event TestHandler TestEvent1
    {
        add
        {
            // smart code to access the private field in a safe way,
            // combining parameter 'value' into that
        }
        remove
        {
            // smart code to access the private field in a safe way,
            // taking out parameter 'value' from that
        }
    }
    public static event TestHandler TestEvent2
    {
        add
        {
            // smart code to access the private field in a safe way,
            // combining parameter 'value' into that
        }
        remove
        {
            // smart code to access the private field in a safe way,
            // taking out parameter 'value' from that
        }
    }
}
相关问题