2012-03-31 53 views
11

我试图初始化用绳子元素作为键的字典和int []元素值,如下所示:创建阵列字典作为值

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

但调试口口声声说:“意外的符号'{'”。

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

谢谢!

回答

8

我不知道C#的,但在Java中,以下作品为例:

代替

{1,1} 

尝试

new int[]{1,1} 

new[]{1,1} 
+2

或者只是'new [] {1,1}'如果你愿意。 – drch 2012-03-31 22:50:40

+0

谢谢!它现在起作用了! – Jodll 2012-04-01 11:32:22

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

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

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

下面是工作的两个例子。第二个例子只在一个方法内工作。第一个例子将在一个方法内部或者在一个类的方法外部工作。

初始代码缺少新的Dictionary()语句的(),这可能是给出了“{”未显示的符号错误。 “新的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} }, 
     }; 

    } 
} 
1

除了所有的好答案,你也可以试试这个。

Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>(); 

如果可能更喜欢清单<>在数组作为调整大小是在阵列困难。您不能从数组中删除元素。但是一个元素可以从List中删除。