我正在创建一个不可变类。
我已将所有属性标记为只读。
我在该类中有一个项目列表。
尽管属性是只读的,但列表仍然可以被修改。
公开列表的 IEnumerable 使其成为不可变的。
我想知道创建不可变类需要遵循哪些基本规则?
我正在创建一个不可变类。
我已将所有属性标记为只读。
我在该类中有一个项目列表。
尽管属性是只读的,但列表仍然可以被修改。
公开列表的 IEnumerable 使其成为不可变的。
我想知道创建不可变类需要遵循哪些基本规则?
我认为你走在了正确的道路上 -
为实现不可变性,您的所有属性和字段都应该是只读的。而任何列表中的项目本身也应该是不可变的。
您可以按如下方式创建一个只读的列表属性:
public class MyClass
{
public MyClass(..., IList<MyType> items)
{
...
_myReadOnlyList = new List<MyType>(items).AsReadOnly();
}
public IList<MyType> MyReadOnlyList
{
get { return _myReadOnlyList; }
}
private IList<MyType> _myReadOnlyList
}
另外需要注意的是:
public readonly object[] MyObjects;
即使使用readonly关键字标记,数组仍然不是不可变的。您仍然可以通过索引访问器更改单个数组引用/值。
你所需要的只是使用 record
和新版本的 C# 9.0 或更新版本。
public record Customer(string FirstName, string LastName, IEnumerable<string> Items);
//...
var person = new Customer("Test", "test", new List<string>() { "Test1", "Test2", "Test3" });
// you can't change anything within person variable
// person.FirstName = "NewName";
这将被翻译成一个不可变的类,称为Customer,它有三个属性:FirstName
, LastName
和 Items
。
如果你需要一个类的属性是不可变的(只读)集合,最好将其公开为IEnumerable<T>
或ReadOnlyCollection<T>
,而不是来自System.Collections.Immutable
的东西。
ReadOnlyCollection
类。它位于System.Collections.ObjectModel
命名空间中。using System.Collections.ObjectModel;
...
public MyClass(..., List<ListItemType> theList, ...)
{
...
this.myListItemCollection= theList.AsReadOnly();
...
}
public ReadOnlyCollection<ListItemType> ListItems
{
get { return this.myListItemCollection; }
}
原子性
、易变性
和不可变性
这些术语的博客系列:第一部分,第二部分和第三部分。这些来自他个人博客,我相信比他在MSDN上的文章更适合新手阅读。 - John Doe