简体   繁体   English

将对象添加到C#中的列表

[英]Add objects to list in C#

When adding to a list in C#, I am getting the same object: 在C#中添加到列表时,我得到了相同的对象:

List<Group> group = new List<Group>();
        Group groupclass=new Group();
        if (this.OpenConnection() == true)
        {
            sql_cmd = new MySqlCommand("listofgroup", sql_con);
            sql_cmd.CommandType = CommandType.StoredProcedure;
            sql_cmd.Parameters.AddWithValue("@userid", userid).Direction = ParameterDirection.Input;
            MySqlDataReader sdr = sql_cmd.ExecuteReader();
            while (sdr.Read())
            {
                groupclass.groupName = sdr.GetString("group_name");
                groupclass.groupID = sdr.GetString("ID");
                group.Add(groupclass);
            }
            this.CloseConnection();
        }
        return group;

As your code stands you only create the object once. 按照您的代码立场,您只需创建一次对象。 When you set the properties inside the while you are setting the values on the original object. 当您在中设置属性时,将在原始对象上设置值。

Instead you need to create the object inside the while 相反,您需要在while内创建对象

while (sdr.Read())
{
    Group groupclass = new Group();
    groupclass.groupName = sdr.GetString("group_name");
    groupclass.groupID = sdr.GetString("ID");
    group.Add(groupclass);
}

You're only creating one Group object, overwriting the values in it, and adding the same object to the list each time. 您仅创建一个Group对象,覆盖其中的值,并且每次都将相同的对象添加到列表中。 You need to move your allocation inside the while loop: 您需要在while循环内移动分配:

while (sdr.Read())
{
    Group groupclass = new Group();
    groupclass.groupName = sdr.GetString("group_name");
    groupclass.groupID = sdr.GetString("ID");
    group.Add(groupclass);
}

You are reusing the same Group instance and re-adding it. 您正在重用相同的Group实例并重新添加它。 Create a new Group instance in the while loop. 在while循环中创建一个新的Group实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM