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

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

问题描述

在 SO 上的讨论之后,我已经多次阅读了关于可变结构是邪恶的"的评论(就像在这个 问题).

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天全站免登陆