簡體   English   中英

C#中的字典數組

[英]Array of dictionaries in C#

我想用這樣的東西:

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

但是,當我這樣做時:

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

它拋出“'TargetInvocationException'...調用目標拋出了異常。”

問題是什么? 我正確使用那個字典數組嗎?

試試這個:

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

您需要先在數組中實例化字典,然后才能使用它們。

您是否將數組對象設置為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");
Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];

這樣做會分配數組'matrix',但是那個應該包含在該數組中的字典永遠不會被實例化。 您必須使用new關鍵字在數組的所有單元格中創建一個Dictionary對象。

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

你已經初始化了數組,但沒有初始化字典。 您需要初始化matrix [0](盡管這應該導致空引用異常)。

你忘了初始化詞典。 添加項目之前,請在下面添加以下行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM