亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C# 編輯列表中的上一個數組

C# 編輯列表中的上一個數組

C#
紫衣仙女 2023-09-09 16:51:41
大家好,我想做一件簡單的事情:我定義了一個字符串類型的列表。然后,我向數組“行”添加一些文本。一段時間后,我想編輯以前的“行”數組并更改例如行[1]。例如:{ { "text1", "text2", "text3" },   { "text4", "text5", "text6" },   { "text7", "text8", "text9"} };所以我想更改列表“行”中的“text5”。我當前的代碼:List<string[]> rows = new List<string[]>();string[] row = new string[3];row[0] = "text1";row[1] = "text2;row[2] = "text3;rows.Add(row);row[0] = "text4";row[1] = "text5;row[2] = "text6;rows.Add(row);row[0] = "text7";row[1] = "text8;row[2] = "text9;rows.Add(row);那么如何編輯“text5”呢?
查看完整描述

2 回答

?
陪伴而非守候

TA貢獻1757條經驗 獲得超8個贊

您的代碼無法按預期工作,因為數組是引用類型。和


new string[3];

您創建一個數組對象。和


rows.Add(row);

您將指向該對象的引用添加到列表中。您沒有添加數組的副本。因此,調用rows.Add(row);3 次后,這 3 行將全部包含對相同且唯一數組的引用。每行將包含{ "text7", "text8", "text9" }


您必須為每一行創建一個新數組。


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);

或者,使用數組初始值設定項


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" });

或者,通過組合集合和數組初始值設定項


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列表已包含對此數組的引用row,因此現在

rows[1][1] == row[1]和rows[1][1] == "new text 5"。即,您不需要替換列表中的行。


查看完整回答
反對 回復 2023-09-09
?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

例如根據您的代碼:


// Use SetValue method

rows[1].SetValue("new value of text5", 1);


// or just by index

rows[1][1] = "new value of text5";


查看完整回答
反對 回復 2023-09-09
  • 2 回答
  • 0 關注
  • 132 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號