用C#组成多播委托-我应该使用运算符还是Action.Combine? [英] Composing multicast delegates in C# - should I use operators or Action.Combine?

查看:117
本文介绍了用C#组成多播委托-我应该使用运算符还是Action.Combine?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读文档,我发现 + 运算符可用于组成/组合相同类型的委托。

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

以同样的方式,我可以使用-运算符从组合的委托中删除a。

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

我还注意到, Action 类型具有静态的 Combine Remove 方法可用于连接两个代表的调用列表,并分别从另一个代表的调用列表中删除一个代表的调用列表。

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.

我已经看到了SO和其他代码中各种示例中使用的两种方式。我是否应该使用一种或另一种方式?有坑坑洼洼吗?例如-我在 a-= b;行中看到一条警告; 指出 Delegate减法有不可预测的结果-所以我应该通过使用Remove来避免这种情况吗?

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?

推荐答案

委托运算符( + -)是静态方法的简写。

根本没有区别。

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

a + = b 编译为 a =(Action)Delegate.Combine(a,b)

这篇关于用C#组成多播委托-我应该使用运算符还是Action.Combine?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆