如何创建一个不可变的类? [英] How do I create an immutable Class?

查看:135
本文介绍了如何创建一个不可变的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作创造一个不可变类。
我已标记的所有属性为只读。

I am working on creating an immutable class.
I have marked all the properties as read-only.

我在类的项目清单。
但如果该属性是只读的,可以在列表中修改。

I have a list of items in the class.
Although if the property is read-only the list can be modified.

揭露列表的IEnumerable使得它一成不变的。
我想知道什么是必须遵循,使一类不可变的基本规则?

Exposing the IEnumerable of the list makes it immutable.
I wanted to know what is the basic rules one has to follow to make a class immutable ?

感谢。

推荐答案

我认为你是在正确的轨道 -

I think you're on the right track -

  • 注入类的所有信息应在构造函数中提供的
  • 在所有属性都应该是唯一的干将
  • 如果一个集合(或阵列)传递到构造函数,它应该被复制,以保持来电者后对其进行修改
  • 如果你要回你的收藏,要么返回副本或只读版本(例如,使用<一个href="http://msdn.microsoft.com/en-us/library/system.collections.arraylist.readonly.aspx">ArrayList.ReadOnly或类似的 - 你可以结合这与previous点的存储的一个只读副本时,呼叫者访问被返回),返回一个枚举器,或使用一些其他的方法/属性,允许只读访问到集合
  • 请记住,你仍然可以有一个可变类的外观,如果你的任何成员都是可变的 - 如果是这样的话,你应该复制走什么状态,你会希望保留并避免返回全可变对象,除非您来电让他们回来之前将它们复制 - 另一种选择是返回可变对象的唯一不变的部分 - 感谢@布赖恩拉斯穆森鼓励我,扩大了这一点
  • all information injected into the class should be supplied in the constructor
  • all properties should be getters only
  • if a collection (or Array) is passed into the constructor, it should be copied to keep the caller from modifying it later
  • if you're going to return your collection, either return a copy or a read-only version (for example, using ArrayList.ReadOnly or similar - you can combine this with the previous point and store a read-only copy to be returned when callers access it), return an enumerator, or use some other method/property that allows read-only access into the collection
  • keep in mind that you still may have the appearance of a mutable class if any of your members are mutable - if this is the case, you should copy away whatever state you will want to retain and avoid returning entire mutable objects, unless you copy them before giving them back to the caller - another option is to return only immutable "sections" of the mutable object - thanks to @Brian Rasmussen for encouraging me to expand this point

这篇关于如何创建一个不可变的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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