【问题标题】:Array of dictionaries in C#C#中的字典数组
【发布时间】:2012-03-07 06:10:55
【问题描述】:

我想用这样的东西:

Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];

但是,当我这样做时:

matrix[0].Add(0, "first str");

它抛出“'TargetInvocationException'...异常已被调用的目标抛出。”

有什么问题?我是否正确使用了该字典数组?

【问题讨论】:

  • 嗯,你应该得到一个NullReferenceException。显示更多代码。
  • 您是否将matrix[0] 初始化为新的Dictionary&lt;int, string&gt;?此外,TargetInvocationExceptionSystem.Reflection 命名空间的一部分。你在哪里使用反射?

标签: c# arrays dictionary


【解决方案1】:

试试这个:

Dictionary<int, string>[] matrix = new Dictionary<int, string>[] 
{
    new Dictionary<int, string>(),
    new Dictionary<int, string>()
};

您需要先实例化数组中的字典,然后才能使用它们。

【讨论】:

  • 您也可以将“new Dictionary[]”简化为“new []”
  • 简洁优雅!
【解决方案2】:

您是否将数组对象设置为 Dictionary 的实例?

Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];
matrix[0] = new Dictionary<int, string>();
matrix[1] = new Dictionary<int, string>();
matrix[0].Add(0, "first str");

【讨论】:

    【解决方案3】:
    Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];
    

    这样做会分配数组“矩阵”,但本应包含在该数组中的字典永远不会被实例化。您必须使用 new 关键字在数组中的所有单元格中创建一个 Dictionary 对象。

    matrix[0] = new Dictionary<int, string>();
    matrix[0].Add(0, "first str");
    

    【讨论】:

      【解决方案4】:

      您已经初始化了数组,但没有初始化字典。您需要初始化 matrix[0] (尽管这会导致空引用异常)。

      【讨论】:

        【解决方案5】:

        您忘记初始化字典。只需在 添加项目之前添加以下行:

        matrix[0] = new Dictionary<int, string>();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多