我想要初始化一个字典,以字符串元素为键,int[]类型的元素为值,如下所示:
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string,int[]>{{"length",{1,1}},{"width",{1,1}}};
但是调试器一直显示:"意外的符号'{'"。
你能告诉我上面的代码有什么问题吗?
谢谢!
我想要初始化一个字典,以字符串元素为键,int[]类型的元素为值,如下所示:
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string,int[]>{{"length",{1,1}},{"width",{1,1}}};
但是调试器一直显示:"意外的符号'{'"。
你能告诉我上面的代码有什么问题吗?
谢谢!
我不确定C#是否适用,但以下代码在Java中可以使用:
而不是
{1,1}
尝试
new int[]{1,1}
或者new[]{1,1}
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} },
};
}
}
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> { { "length", new int[] { 1, 1 } }, { "width", new int[] { 1, 1 } } };
System.Collections.Generic.Dictionary<string, int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> {{"length", new int[]{1,2}},{ "width",new int[]{3,4}}};
Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
如果可能的话,优先使用List<>而不是数组,因为在数组中调整大小很困难。您无法从数组中删除元素。但是可以从List中删除元素。
new[] {1,1}
。 - drch