在C#编写的多播的代表 - 我用768,16运算符或Action.Combine? [英] Composing multicast delegates in C# - shoud I use operators or Action.Combine?

查看:241
本文介绍了在C#编写的多播的代表 - 我用768,16运算符或Action.Combine?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读文档,我可以看到 + 操作符可以用来撰写/组合相同类型的代表。

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.

我已经看到了各种示例中使用的SO和其他代码两种方式。有,我应该用一种方式或其他理由吗?是否有坑瀑布?例如 - 我可以在该行看到警告 A - = B; 说明代表减法具有不可预知的结果 - 所以,我应该使用删除避免这种情况?

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 =(动作)Delegate.Combine(A,b)

这篇关于在C#编写的多播的代表 - 我用768,16运算符或Action.Combine?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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