对于不可变的数据,冻结字典能很大程度提高效率。
private FrozenDictionary<int, string> frozen;
private void InitializeFrozenDictionary()
{
var frozenDict = new Dictionary<int, string>
{
{ 1, "one" },
{ 2, "two" },
{ 3, "three" }
};
// 尝试添加新元素
frozenDict.TryAdd(4, "four");
// 将字典转换为 FrozenDictionary
frozen = frozenDict.ToFrozenDictionary();
}