永恒的真正定义是什么? [英] The true definition of immutability?

查看:131
本文介绍了永恒的真正定义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何不变性的定义?如果值不公开为公,所以不能被修改,那么它是足够了吗?

能的值来内型改性,而不是由类型的客户?

或者可以在一个只有一个构造函数中设置呢?如果是这样,在双初始化的情况下(使用的结构这关键字等)仍然是确定恒定类型?

我怎么能保证类型是100%的不可变的?

解决方案
  

如果该值不公开为公,所以不能被修改,那么它是足够了吗?

没有,因为你需要读取权限。

  

能的值来内型改性,而不是由类型的客户?

没有,因为这仍然突变。

  

或者可以在一个只有一个构造函数中设置呢?

丁顶顶!随着更多的点不变类型通常有构建并返回新实例,并且还经常有额外的构造标记方法内部专供这些方法使用。

  

我怎么能保证类型是100%的不可变的?

在净它的棘手得到这样的保证,因为你可以使用反射来修改(变异)的私有成员。

I am wondering how immutability is defined? If the values aren't exposed as public, so can't be modified, then it's enough?

Can the values be modified inside the type, not by the customer of the type?

Or can one only set them inside a constructor? If so, in the cases of double initialization (using the this keyword on structs, etc) is still ok for immutable types?

How can I guarantee that the type is 100% immutable?

解决方案

If the values aren't exposed as public, so can't be modified, then it's enough?

No, because you need read access.

Can the values be modified inside the type, not by the customer of the type?

No, because that's still mutation.

Or can one only set them inside a constructor?

Ding ding ding! With the additional point that immutable types often have methods that construct and return new instances, and also often have extra constructors marked internal specifically for use by those methods.

How can I guarantee that the type is 100% immutable?

In .Net it's tricky to get a guarantee like this, because you can use reflection to modify (mutate) private members.

这篇关于永恒的真正定义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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