创建一个字典,其值为数组。

19

我想要初始化一个字典,以字符串元素为键,int[]类型的元素为值,如下所示:

System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string,int[]>{{"length",{1,1}},{"width",{1,1}}};

但是调试器一直显示:"意外的符号'{'"。

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

谢谢!

5个回答

13

我不确定C#是否适用,但以下代码在Java中可以使用:

而不是

{1,1}

尝试

new int[]{1,1}
或者
new[]{1,1}

2
如果你喜欢的话,或者简单地使用 new[] {1,1} - drch
对于任何好奇并想要更多信息的人,就像我一样,请在此处查看 https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/ - theYnot

9
以下是两个可行的示例。第二个示例只在方法内部起作用。第一个示例可以在类中的方法内或方法外使用。
初始代码缺少()符号,该符号在新字典()语句中很可能造成了“{”未预期的符号错误。还需要“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} },
        };

    }
}

6
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
        myDictionary = new Dictionary<string, int[]> { { "length", new int[] { 1, 1 } }, { "width", new int[] { 1, 1 } } };

5
你需要指定你要将一个数组插入到字典中:
System.Collections.Generic.Dictionary<string, int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> {{"length", new int[]{1,2}},{ "width",new int[]{3,4}}};

3
除了所有好的答案,您还可以尝试这个。
Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();

如果可能的话,优先使用List<>而不是数组,因为在数组中调整大小很困难。您无法从数组中删除元素。但是可以从List中删除元素。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接