不可变的收藏品
该 System.Collections.Immutable
NuGet 包提供不可变的集合类。
创建和添加项目
var stack = ImmutableStack.Create<int>();
var stack2 = stack.Push(1); // stack is still empty, stack2 contains 1
var stack3 = stack.Push(2); // stack2 still contains only one, stack3 has 2, 1
使用构建器创建
某些不可变集合有一个 Builder
内部类,可用于廉价构建大型不可变实例:
var builder = ImmutableList.CreateBuilder<int>(); // returns ImmutableList.Builder
builder.Add(1);
builder.Add(2);
var list = builder.ToImmutable();
从现有的 IEnumerable 创建
var numbers = Enumerable.Range(1, 5);
var list = ImmutableList.CreateRange<int>(numbers);
所有不可变集合类型的列表:
System.Collections.Immutable.ImmutableArray<T>
System.Collections.Immutable.ImmutableDictionary<TKey,TValue>
System.Collections.Immutable.ImmutableHashSet<T>
System.Collections.Immutable.ImmutableList<T>
System.Collections.Immutable.ImmutableQueue<T>
System.Collections.Immutable.ImmutableSortedDictionary<TKey,TValue>
System.Collections.Immutable.ImmutableSortedSet<T>
System.Collections.Immutable.ImmutableStack<T>