创建一个以数组作为值的字典

Jod*_*dll 15 c# dictionary

我正在尝试初始化一个字符串元素作为键和int []元素作为值的字典,如下所示:

System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string,int[]>{{"length",{1,1}},{"width",{1,1}}};
Run Code Online (Sandbox Code Playgroud)

但调试器一直说:"意外的符号'{'".

你能告诉我上面的代码有什么问题吗?

谢谢!

kas*_*ere 9

我不确定c#,但以下是Java中的工作:

代替

{1,1}
Run Code Online (Sandbox Code Playgroud)

尝试

new int[]{1,1}
Run Code Online (Sandbox Code Playgroud)

要么

new[]{1,1}
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`new [] {1,1}`如果你愿意的话. (2认同)

小智 7

以下是两个有效的例子.第二个示例仅适用于方法.第一个示例将在方法内部或在类中的方法外部工作.

初始代码缺少新的Dictionary()语句的(),这可能是"{"未发现的符号错误."new Int []"也是必需的

class SomeClass
{
    Dictionary<string, int[]> myDictionary = new Dictionary<string, int[]>()
    {
        {"length", new int[] {1,1} },
        {"width", new int[] {1,1} },
    };

    public void SomeMethod()
    {
        Dictionary<string, int[]> myDictionary2;
        myDictionary2 = new Dictionary<string, int[]>()
        {
            {"length", new int[] {1,1} },
            {"width", new int[] {1,1} },
        };

    }
}
Run Code Online (Sandbox Code Playgroud)


Sta*_*tar 5

System.Collections.Generic.Dictionary<string,int[]> myDictionary;
        myDictionary = new Dictionary<string, int[]> { { "length", new int[] { 1, 1 } }, { "width", new int[] { 1, 1 } } };
Run Code Online (Sandbox Code Playgroud)


Nic*_*las 5

您将需要指定它是要插入字典的数组:

System.Collections.Generic.Dictionary<string, int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> {{"length", new int[]{1,2}},{ "width",new int[]{3,4}}};
Run Code Online (Sandbox Code Playgroud)