这个 Dictionary 初始值设定项有什么问题

What is wrong with this Dictionary initializer

我可能完全失明了,但我看不出这段代码有什么问题:

public static Dictionary<States, string> NameMap = new Dictionary<States, string>
{
    [States.State1] = "State1",
    [States.State2] = "State2",
    [States.State3] = "State3",
    [States.State4] = "State4",
    [States.State5] = "State5",
    [States.State6] = "State6"
};

尝试构建时,我听到了这些错误:

Invalid expression term '['

(这指向每行的第一个括号)

Syntax error, ',' expected

这指向 * 列:

[States*.State1]* = "State1",

如有任何帮助,我们将不胜感激。通过 .Add 将这些值放入工作正常。

顺便说一句,States 是一个枚举。

问题是由 Resharper 引起的,只是假设我使用的是 C# 6 编译器并且 'correcting' 我的代码相应。经查,我用的不是C#6,幸亏Resharper我没删

你的语法是正确的!

你可以在这里测试:http://www.volatileread.com/utilitylibrary/snippetcompiler?id=69450

这称为索引初始值设定项

Object and collection initializers are useful for declaratively initializing fields and properties of objects, or giving a collection an initial set of elements. Initializing dictionaries and other objects with indexers is less elegant. We are adding a new syntax to object initializers allowing you to set values to keys through any indexer that the new object has

var numbers = new Dictionary<int, string> {
    [7] = "seven",
    [9] = "nine",
    [13] = "thirteen"
};

来源:https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6