Array of dictionaries in C#

后端 未结 5 1741
挽巷
挽巷 2020-12-15 05:42

I would like to use something like this:

Dictionary[] matrix = new Dictionary[2];

But, when I do:

相关标签:
5条回答
  • 2020-12-15 05:58

    You forgot to initialize the Dictionary. Just put the line below before adding the item:

    matrix[0] = new Dictionary<int, string>();
    
    0 讨论(0)
  • 2020-12-15 06:06

    Try this:

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

    You need to instantiate the dictionaries inside the array before you can use them.

    0 讨论(0)
  • 2020-12-15 06:13
    Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];
    

    Doing this allocates the array 'matrix', but the the dictionaries supposed to be contained in that array are never instantiated. You have to create a Dictionary object in all cells in the array by using the new keyword.

    matrix[0] = new Dictionary<int, string>();
    matrix[0].Add(0, "first str");
    
    0 讨论(0)
  • 2020-12-15 06:16

    You've initialized the array, but not the dictionary. You need to initialize matrix[0] (though that should cause a null reference exception).

    0 讨论(0)
  • 2020-12-15 06:18

    Did you set the array objects to instances of 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");
    
    0 讨论(0)
提交回复
热议问题