Composing multicast delegates in C# - should I use operators or Action.Combine?

狂风中的少年 提交于 2019-12-01 16:38:30

问题


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:


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)



来源:https://stackoverflow.com/questions/14197857/composing-multicast-delegates-in-c-sharp-should-i-use-operators-or-action-comb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!