不可變的收藏品
該 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>