我已经定义了motorData类,如下所示:
public class motorData
{
public int data0 { get; set; }
public int data1 { get; set; }
public int data2 { get; set; }
public int data3 { get; set; }
public int data4 { get; set; }
public int data5 { get; set; }
public int data6 { get; set; }
public int data7 { get; set; }
public int data8 { get; set; }
}
该类用于Button
点击事件,如下所示:
List<motorData> mtdlist = new List<motorData>();
motorData mtd = new motorData();
private void button2_Click_1(object sender, EventArgs e)
{
mtd.data0 = 1;
mtdlist.Add(mtd);
mtd.data0 = 2;
mtdlist.Add(mtd);
mtd.data0 = 3;
mtdlist.Add(mtd);
mtd.data0 = 4;
mtdlist.Add(mtd);
mtd.data0 = 5;
mtdlist.Add(mtd);
}
在调用该事件后,我得到以下结果:
mtdlist[0].data0 = 5;
mtdlist[1].data0 = 5;
mtdlist[2].data0 = 5;
mtdlist[3].data0 = 5;
mtdlist[4].data0 = 5;
如果我将motorData定义为结构,我会得到正确的结果。那我错过了什么?
答案 0 :(得分:1)
您要将值分配给同一个对象,您应该每次都创建新的Object。
List<motorData> mtdlist = new List<motorData>();
private void button2_Click_1(object sender, EventArgs e)
{
motorData mtd1 = new motorData();
mtd1.data0 = 1;
mtdlist.Add(mtd1);
motorData mtd2 = new motorData();
mtd2.data0 = 2;
mtdlist.Add(mtd2);
motorData mtd3 = new motorData();
mtd3.data0 = 3;
mtdlist.Add(mtd3);
motorData mtd4 = new motorData();
mtd4.data0 = 4;
motorData mt5 = new motorData();
mtdlist.Add(mtd4);
mtd5.data0 = 5;
mtdlist.Add(mtd5);
}
的更多信息