问题描述
我想写这样的东西:
var d = new ImmutableDictionary<string, int> { { "a", 1 }, { "b", 2 } };
(使用来自 System.Collections.ImmutableImmutableDictionary/a>).这似乎是一个简单的用法,因为我预先声明了所有值——那里没有突变.但这给了我错误:
(using ImmutableDictionary
from System.Collections.Immutable). It seems like a straightforward usage as I am declaring all the values upfront -- no mutation there. But this gives me error:
类型 'System.Collections.Immutable.ImmutableDictionary
' 没有定义构造函数
我应该如何使用静态内容创建一个新的不可变字典?
How I am supposed to create a new immutable dictionary with static content?
推荐答案
您不能使用集合初始值设定项创建不可变集合,因为编译器将它们转换为对 Add
方法的调用序列.例如,如果您查看 var d = new Dictionary 的 IL 代码;{ { "a", 1 }, { "b", 2 } };
你会得到
You can't create immutable collection with a collection initializer because the compiler translates them into a sequence of calls to the Add
method. For example if you look at the IL code for var d = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } };
you'll get
IL_0000: newobj instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::.ctor()
IL_0005: dup
IL_0006: ldstr "a"
IL_000b: ldc.i4.1
IL_000c: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::Add(!0, !1)
IL_0011: dup
IL_0012: ldstr "b"
IL_0017: ldc.i4.2
IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::Add(!0, !1)
显然这违反了不可变集合的概念.
Obviously this violates the concept of immutable collections.
你自己的回答和 Jon Skeet 的回答都是解决这个问题的方法.
Both your own answer and Jon Skeet's are ways to deal with this.
// lukasLansky's solution
var d = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } }.ToImmutableDictionary();
// Jon Skeet's solution
var builder = ImmutableDictionary.CreateBuilder<string, int>();
builder.Add("a", 1);
builder.Add("b", 2);
var result = builder.ToImmutable();
这篇关于如何创建 ImmutableDictionary 的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!