将元素添加到类列表中

时间:2014-06-12 12:22:07

标签: c# list class

我已经定义了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定义为结构,我会得到正确的结果。那我错过了什么?

1 个答案:

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

}

了解有关Structure vs Class

的更多信息