在C#中,不变量代表的目的是什么? [英] What is the purpose of the delegates are immutable in c#?

查看:53
本文介绍了在C#中,不变量代表的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读《组合代表点》一节中说明了C#2012的书,没有注意到吗?代表的目的是一成不变的。

I was reading a book illustrated C # 2012 in the section Combining Delegates point not notice that? Purpose of the delegates are immutable.


合并代表
到目前为止,您看到的所有代表都只有$ b $在其调用列表中的单个方法。可以使用加法运算符将代表组合
。该操作的结果是
创建一个新的委托,其调用列表是两个操作数
委托的调用列表副本的
串联。例如,以下代码创建三个委托。
第三个委托是根据前两个的组合创建的。

Combining Delegates All the delegates you’ve seen so far have had only a single method in their invocation lists. Delegates can be "combined" by using the addition operator. The result of the operation is the creation of a new delegate, with an invocation list that is the concatenation of copies of the invocation lists of the two operand delegates. For example, the following code creates three delegates. The third delegate is created from the combination of the first two.



MyDel delA = myInstObj.MyM1;
MyDel delB = SClass.OtherM2;
MyDel delC = delA + delB; // Has combined invocation list




印象
操作数委托已被修改,它们根本没有被更改。实际上,代表是不可变的。创建委托对象后,不能更改
。图15-6说明了前面
代码的结果。请注意,操作数委托保持不变。

Although the term combining delegates might give the impression that the operand delegates are modified, they are not changed at all. In fact, delegates are immutable. After a delegate object is created, it cannot be changed. Figure 15-6 illustrates the results of the preceding code. Notice that the operand delegates remain unchanged.

推荐答案

线程安全性和速度是这里的主要问题。委托更新不是原子更新,它需要更新6个字段和一个列表。使其原子化以使其不会损坏需要锁定,而对于这样的基本操作而言,它太昂贵了,而这样的基本操作很少需要 是线程安全的。

Thread-safety and speed are the primary concerns here. A delegate update is not atomic, it requires updating 6 fields and a list. Making it atomic so it cannot get corrupted requires a lock, far too expensive for such a basic operation that rarely needs to be thread-safe.

通过使其不可变,委托对象不会被破坏,因为它总是在对象上设置字段,而该对象尚无人引用。重新分配委托对象引用是原子的,这是基本的.NET内存模型保证。因此,不再需要锁定。权衡是内存使用效率较低,这是一个小小的惩罚。

By making it immutable, the delegate object cannot get corrupted since it always sets fields on an object that nobody has a reference to yet. Reassigning the delegate object reference is atomic, a basic .NET memory model guarantee. So no need for a lock anymore. The trade-off is less efficient memory use, it is a small penalty.

请记住,线程安全的委托更新不会自动使您的代码成为线程-安全。测试和发射代码需要复制引用以避免NRE,您可以对尚未取消订阅的方法进行回调。

Do keep in mind that the thread-safe delegate update does not automatically make your code thread-safe as well. The test-and-fire code needs to copy the reference to avoid NRE and you can make a callback to a method that was already unsubscribed.

这篇关于在C#中,不变量代表的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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