azr*_*n92 447 c# dictionary
我正在使用以下代码在C#文件中创建字典:
private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT
= new Dictionary<string, XlFileFormat>
{
{"csv", XlFileFormat.xlCSV},
{"html", XlFileFormat.xlHtml}
};
Run Code Online (Sandbox Code Playgroud)
new错误下面有一条红线:
无法使用功能'集合initilializer',因为它不是ISO-2 C#语言规范的一部分
谁能解释一下这里发生了什么?
编辑:好的,所以事实证明我使用的是.NET版本2.
Han*_*ney 728
我无法在简单的.NET 4.0控制台应用程序中重现此问题:
static class Program
{
static void Main(string[] args)
{
var myDict = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试在简单的控制台应用程序中重现它并从那里开始吗?您似乎可能是针对.NET 2.0(不支持它)或客户端配置文件框架,而不是支持初始化语法的.NET版本.
Vik*_*mar 180
使用C#6.0,您可以通过以下方式创建字典:
var dict = new Dictionary<string, int>
{
["one"] = 1,
["two"] = 2,
["three"] = 3
};
Run Code Online (Sandbox Code Playgroud)
它甚至适用于自定义类型.
Bre*_*dan 34
您可以Dictionary内联初始化(和其他集合).每个成员都包含大括号:
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
{ 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
{ 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
{ 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅MSDN
Deb*_*ash 17
假设我们有这样的字典
Dictionary<int,string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");
Run Code Online (Sandbox Code Playgroud)
我们可以按如下方式初始化它.
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "Mohan" },
{ 2, "Kishor" },
{ 3, "Pankaj" },
{ 4, "Jeetu" }
};
Run Code Online (Sandbox Code Playgroud)
Ed'*_*'ka 16
请注意,C# 9 允许目标类型的新表达式,因此如果您的变量或类成员不是抽象类或接口类型,则可以避免重复:
private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT = new ()
{
{ "csv", XlFileFormat.xlCSV },
{ "html", XlFileFormat.xlHtml }
};
Run Code Online (Sandbox Code Playgroud)
与 \xd0\xa1# 6.0
\nvar myDict = new Dictionary<string, string>\n{\n ["Key1"] = "Value1",\n ["Key2"] = "Value2"\n};\nRun Code Online (Sandbox Code Playgroud)\n