开发者

In .NET why does event connection order matter like this?

u开发者_如何转开发sing System;

static class Program
{
    static event Action A = delegate { };
    static event Action B = delegate { };

    static void Main()
    {
        A += B;
        B += ()=>Console.WriteLine("yeah");
        A.Invoke();
    }
}

This doesn't print anything, but if I swap the first two lines of Main, it does.


Events are immutable, i.e. you get a copy when assigning, like integers

int a = 1;
int b = 2;

a += b; // a == 3
b += 1; // a is still 3


A += B; is appending the list of delegates from B into A. It is copying the contents of B, not a reference to B.

It is the same as:

A = (Action)System.Delegate.Combine(A, B);

So the order is definitely important.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜