Composing multicast delegates in C# - should I use

2020-04-05 08:07发布

Reading the documentation I can see that + operator can be used to compose/combine delegates of the same type.

In the same way I can see that I can remove a from the composed delegate using the - operator.

I also noticed that the Action type has static Combine and Remove methods that can be used to concatenate the invocation lists of two delegates, and to remove the last occurrence of the invocation list of a delegate from the invocation list of another delegate respectively.

        Action a = () => Debug.WriteLine("Invoke a");
        Action b = () => Debug.WriteLine("Invoke b");
        a += b;
        a.Invoke(); 

        //Invoke a
        //Invoke b

        Action c = () => Debug.WriteLine("Invoke c");
        Action d = () => Debug.WriteLine("Invoke d");
        Action e = Action.Combine(c, d);
        e.Invoke();

        //Invoke c
        //Invoke d

        a -= b;
        a.Invoke();

        //Invoke a

        e = Action.Remove(e, d);
        e.Invoke(); 

        //Invoke c

They appear to produce the same results in terms of how they combine/remove from the invocation list.

I have seen both ways used in various examples on SO and in other code. Is there a reason that I should be using one way or the other? Are there any pit falls? For example - I can see a warning in the line a -= b; stating that Delegate subtraction has unpredictable results - so should I avoid this by using Remove?

1条回答
smile是对你的礼貌
2楼-- · 2020-04-05 08:44

The delegate operators (+ and -) are shorthand for the static methods.
There is no difference at all.

a += b compiles to a = (Action)Delegate.Combine(a, b)

查看更多
登录 后发表回答