2 回答

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個(gè)贊
您的代碼無(wú)法按預(yù)期工作,因?yàn)閿?shù)組是引用類型。和
new string[3];
您創(chuàng)建一個(gè)數(shù)組對(duì)象。和
rows.Add(row);
您將指向該對(duì)象的引用添加到列表中。您沒有添加數(shù)組的副本。因此,調(diào)用rows.Add(row);3 次后,這 3 行將全部包含對(duì)相同且唯一數(shù)組的引用。每行將包含{ "text7", "text8", "text9" }
您必須為每一行創(chuàng)建一個(gè)新數(shù)組。
List<string[]> rows = new List<string[]>();
string[] row = new string[3];
row[0] = "text1";
row[1] = "text2";
row[2] = "text3";
rows.Add(row);
row = new string[3];
row[0] = "text4";
row[1] = "text5";
row[2] = "text6";
rows.Add(row);
row = new string[3];
row[0] = "text7";
row[1] = "text8";
row[2] = "text9";
rows.Add(row);
或者,使用數(shù)組初始值設(shè)定項(xiàng)
List<string[]> rows = new List<string[]>();
rows.Add(new string[] { "text1", "text2", "text3" });
rows.Add(new string[] { "text4", "text5", "text6" });
rows.Add(new string[] { "text7", "text8", "text9" });
或者,通過組合集合和數(shù)組初始值設(shè)定項(xiàng)
List<string[]> rows = new List<string[]> {
new string[] { "text1", "text2", "text3" },
new string[] { "text4", "text5", "text6" },
new string[] { "text7", "text8", "text9" }
};
然后您可以使用從零開始的索引訪問“text5”
string oldValue = rows[1][1]; // 1st index selects the row, 2nd the array element.
rows[1][1] = "new text5";
或者
string row = rows[1];
string oldValue = row[1];
row[1] = "new text5";
由于rows列表已包含對(duì)此數(shù)組的引用row,因此現(xiàn)在
rows[1][1] == row[1]和rows[1][1] == "new text 5"。即,您不需要替換列表中的行。

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
例如根據(jù)您的代碼:
// Use SetValue method
rows[1].SetValue("new value of text5", 1);
// or just by index
rows[1][1] = "new value of text5";
- 2 回答
- 0 關(guān)注
- 129 瀏覽
添加回答
舉報(bào)