我正在尝试创建一个包含整数、字符串和布尔值数据类型的数组作为值的字典。我想使用object[]作为值,因此声明如下所示:
每当我尝试将其元素的值设置为某些内容时,VS会提示字典中找不到该键。
Dictionary<long, object[]> netObjectArray = new Dictionary<long, object[]>();
每当我尝试将其元素的值设置为某些内容时,VS会提示字典中找不到该键。
netObjectArray[key][2] = val; // ex: The given key was not present in the dictionary.
我该如何正确处理这个问题?
更新1: 在抛出此异常之前,其他字典以类似的方式使用时没有任何问题:
Dictionary<long, Vector2> netPositions = new Dictionary<long, Vector2>();
netPositions[key] = new Vector2(x, y); // works ok
在这个例子中,locals 显示了已经赋值的内容,字典现在包含该条目。为什么我的其他字典不是这种情况呢?
解决方案: 在写入值到一个值数组之前,我们必须先初始化该数组。以下代码对我有效:
try { netObjectArray[key] = netObjectArray[key]; } // if the object is undefined,
catch { netObjectArray[key] = new object[123]; } // this part will create an object
netObjectArray[key][0] = new Vector2(x, y) as object; // and now we can assign a value to it :)
netObjectArray[key]
初始化至少为new object[2]
? - Albin SunnanboTuple<int,string,bool>
作为值。http://msdn.microsoft.com/zh-cn/library/system.tuple.aspx - Tim SchmelterPlayer
类,并拥有一个Player
字典。 - Servy