從這篇文章中,我可以使用以下內容制作字典陣列:
Dictionary<int, string>[] matrix = new Dictionary<int, string>[]
{
new Dictionary<int, string>(),
new Dictionary<int, string>(),
new Dictionary<int, string>()
};
但是有沒有辦法在不說明所有字典的情況下制作可變長度陣列,例如:
int amountOfDict = 4;
Dictionary<int, string>[] matrix = new Dictionary<int, string>[]
{
//for the amount of amountOfDict, make Dictionaries
};
我很高興使用串列來執行此操作,因為我知道必須宣告陣列。
uj5u.com熱心網友回復:
如果要使用空字典初始化陣列中的所有插槽,請使用簡單的for回圈:
// create array of specified size
Dictionary<int, string>[] matrix = new Dictionary<int, string>[amountDict];
// populate each slot in array with a new empty dictionary
for(int i = 0; i < amountDict; i )
matrix[i] = new Dictionary<int, string>();
如果您真的想要一個可調整大小的可變長度字典集合,請考慮使用 aList<Dictionary<int, string>>而不是陣列:
// create empty list of dictionaries
List<Dictionary<int, string>> matrix = new List<Dictionary<int, string>>();
// add desired amount of new empty dictionaries to list
for(int i = 0; i < amountDict; i )
matrix.Add(new Dictionary<int, string>());
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456420.html
