Guide lines to make a immutable C# classes.
the article is based on the post here: http://stackoverflow.com/questions/352471/how-do-i-create-an-immutable-class
You cannot asssume that the C# language allows you to change the semantic of the assignment oprator, if is to copy the reference on the reference types, and to memberwise copy on the struct types.
To make a class immutable in C#, you basically have to following the rules as follows.
I think you're on the right track -
- 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
本文档提供了创建C#不可变类的基本原则,包括确保所有信息通过构造函数注入、属性仅提供getter、拷贝传递的集合以防止外部修改等。此外还讨论了如何返回只读视图以及处理成员中可能存在的可变性问题。
336

被折叠的 条评论
为什么被折叠?



