c#列表得到相同的值

本文关键字:列表 | 更新日期: 2023-09-27 18:17:32

哦,拜托谁给我解释一下为什么会这样…

public List<EmployeeHeader> GetEmployees()
        {
            List<EmployeeHeader> eh = new List<EmployeeHeader>();
            string query = "SELECT " +
                           "     firstName, lastName " +
                           "FROM" +
                           "     tbEmployee ";
            DBConnect db = new DBConnect();
            DataTable dt = new DataTable();
            dt = db.getBD(query);
            int CountRows = dt.Rows.Count;
            EmployeeHeader emp = new EmployeeHeader();
            for(int i = 0; i < CountRows; i++)
            {
                emp.firstName = dt.Rows[i]["firstName"].ToString();
                emp.lastName = dt.Rows[i]["lastName"].ToString();
                eh.Add(emp);
            }
            return eh;

这是类:

public class EmployeeHeader
    {
        public string firstName { get; set;}
        public string lastName {get; set;}
    }

,最终结果是…

<ArrayOfEmployeeHeader xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.istec.pt/">
<EmployeeHeader>
<firstName>Hugo</firstName>
<lastName>Almeida</lastName>
</EmployeeHeader>
<EmployeeHeader>
<firstName>Hugo</firstName>
<lastName>Almeida</lastName>
</EmployeeHeader>
<EmployeeHeader>
<firstName>Hugo</firstName>
<lastName>Almeida</lastName>
</EmployeeHeader>
<EmployeeHeader>
<firstName>Hugo</firstName>
<lastName>Almeida</lastName>
</EmployeeHeader>
<EmployeeHeader>
<firstName>Hugo</firstName>
<lastName>Almeida</lastName>
</EmployeeHeader>
</ArrayOfEmployeeHeader>

总是相同的名称!!我已经调试,一步一步,正确的名字进入列表,但最后…我得到了相同的名字!!

可能是一个愚蠢的错误,但谁能帮我指出来吗?

谢谢

c#列表得到相同的值

您正在设置同一实例的属性。将下面的行放到循环中:

EmployeeHeader emp = new EmployeeHeader();
        for(int i = 0; i < CountRows; i++)
        {
            EmployeeHeader emp = new EmployeeHeader();
            emp.firstName = dt.Rows[i]["firstName"].ToString();
            emp.lastName = dt.Rows[i]["lastName"].ToString();
            eh.Add(emp);
        }

像这样试试

for(int i = 0; i < CountRows; i++)
        {
            EmployeeHeader emp = new EmployeeHeader();
            emp.firstName = dt.Rows[i]["firstName"].ToString();
            emp.lastName = dt.Rows[i]["lastName"].ToString();
            eh.Add(emp);
        }