[英]Adding item to List<> c#
我有一個2D數組,我試圖寫入一個List,所以我可以綁定它與數據網格。 下面是我的代碼。
string[,] array = new string[8,4];
array[counting2, 0] = txtSend.Text;
array[counting2, 1] = One;
array[counting2, 2] = Two;
array[counting2, 3] = Three;
List<Testing> Hello1 = new List<Testing>();
Testing Hello = new Testing();
for (int i = 0; i <= counting2;i++ )
{
Hello.year = array[counting2, 0];
Hello.One = array[counting2, 1];
Hello.Two = array[counting2, 2];
Hello.Three = array[counting2, 3];
Hello1.Add(Hello);
}
dataGrid1.ItemsSource = Hello1;
可以看到的是,當我的數組包含3行時,數據網格顯示3行,具有相同的數據,而不是3個不同的數據。 我猜是我將Hello添加到列表中3次。
但是我是否將Hello更改為varbele,因此每次for循環都會循環另一個名稱。
Ne Ideas ??
移動聲明
Testing Hello = new Testing();
在循環內
所以你有了;
for (int i = 0; i <= counting2;i++ )
{
Testing Hello = new Testing();
Hello.year = array[counting2, 0];
Hello.One = array[counting2, 1];
Hello.Two = array[counting2, 2];
Hello.Three = array[counting2, 3];
Hello1.Add(Hello);
}
問題正如您所說的那樣:您將相同的元素添加到列表中三次。 而且你每次迭代都會改變它,但它總是相同的對象。 您應該將對象的創建移動到循環中,以便每次都創建不同的對象。
for (int i = 0; i <= counting2;i++ )
{
Testing Hello = new Testing();
Hello.year = array[counting2, 0];
Hello.One = array[counting2, 1];
Hello.Two = array[counting2, 2];
Hello.Three = array[counting2, 3];
Hello1.Add(Hello);
}
更改您的代碼如下所示將工作。 您需要在內部實例化對象,以便每次都是新的
for (int i = 0; i <= counting2;i++ )
{
Testing Hello = new Testing();
Hello.year = array[counting2, 0];
Hello.One = array[counting2, 1];
Hello.Two = array[counting2, 2];
Hello.Three = array[counting2, 3];
Hello1.Add(Hello);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.