结构的不变性 [英] Immutability of structs

查看:217
本文介绍了结构的不变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  为什么是可变的结构邪?

我在很多地方,包括在这里,它是更好地使结构作为永恒不变的阅读。

I read it in lots of places including here that it's better to make structs as immutable.

什么是这背后的原因是什么?我看到很多微软创建的结构体是可变的,像在XNA。也许还有更多的BCL。

What's the reason behind this? I see lots of Microsoft-created structs that are mutable, like the ones in xna. Probably there are many more in the BCL.

什么是不遵守本准则的优点和缺点是什么?

What are the pros and cons of not following this guideline?

推荐答案

结构体应该重新present 。值不会更改。号12是永恒的。

Structs should represent values. Values do not change. The number 12 is eternal.

不过,考虑:

Foo foo = new Foo(); // a mutable struct
foo.Bar = 27;
Foo foo2 = foo;
foo2.Bar = 55;

现在foo.Bar和foo2.Bar不同的是,这往往是意想不到的。尤其是在像性质的情景(幸运的是,编译器检测到这一点)。而且收藏等;怎么你有没有发生变异,他们的理智?

Now foo.Bar and foo2.Bar is different, which is often unexpected. Especially in the scenarios like properties (fortunately the compiler detect this). But also collections etc; how do you ever mutate them sensibly?

数据丢失是远​​与可变结构太容易了。

Data loss is far too easy with mutable structs.

这篇关于结构的不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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