为什么是可变的结构“恶”? [英] Why are mutable structs “evil”?

查看:316
本文介绍了为什么是可变的结构“恶”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里经过讨论,所以我已经看了几遍这句话是可变的结构是邪恶(如在回答这个<一个href=\"http://stackoverflow.com/questions/292676/is-there-a-workaround-for-overloading-the-assignment-operator-in-c\">question).

Following the discussions here on SO I already read several times the remark that mutable structs are "evil" (like in the answer to this question).

什么是与可变性和结构在C#中的实际问题?

What's the actual problem with mutability and structs in C#?

推荐答案

结构是值类型,这意味着当他们被传来传去,他们被复制。

Structs are value types which means they are copied when they are passed around.

所以,如果你改变一个副本,只是更改了该副本,而不是原来的,而不是任何其他副本这可能是各地。

So if you change a copy you are changing only that copy, not the original and not any other copies which might be around.

如果你的结构是不变的,然后从价值传递产生的所有自动副本将是相同的。

If your struct is immutable then all automatic copies resulting from being passed by value will be the same.

如果你想改变它,你必须有意识地通过修改后的数据创建结构的新实例做。 (不是副本)

If you want to change it you have to consciously do it by creating a new instance of the struct with the modified data. (not a copy)

这篇关于为什么是可变的结构“恶”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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