我有这种代码
foreach(GridViewRow row in gvTagDeductionList.Rows)
{
DeductionEntity de = new DeductionEntity();
//modify this condition, make cell number to be more dynamic
if (((CheckBox)row.Cells[2].FindControl("chkInclude")).Checked == true)
{
//following id's are said to be in numeric format in the first place
//ede.EmployeeID = Convert.ToInt32(HttpContext.Current.Session["_newEmpID"].ToString());
ede.DeductionID = Convert.ToInt32((((Label)row.Cells[0].FindControl("lblID")).Text).ToString());
ede.CreatedBy_UserID = Convert.ToInt32(HttpContext.Current.Session["_employeeID"].ToString());
ede.UpdatedBy_UserID = Convert.ToInt32(HttpContext.Current.Session["_employeeID"].ToString());
de = e201u.GetDeductionDetails(ede.DeductionID);
e201u.InsertEmployeeDeduction(ede);
lstEntity.Add(de);
}
}
de = e201u.GetDeductionDetails(ede.DeductionID);
在循环中第二次遇到此代码后,此代码lstEntity.Add(de);
中的第一条记录将被更改,最后我将在最后一个实体的列表中输入两个条目{ {1}}
答案 0 :(得分:3)
在循环内部,您必须再次创建插入列表的对象。现在您只需插入它,然后更改它并再次插入它。您只将对象的引用保存到列表中,而不是实际的对象本身。作为循环的第一行(您尚未显示),请尝试根据ede对象的类型编写ede = new ...()
。
对于所有基于引用的类型(类),同样的“问题”将发生,但对于基于值的类型(结构)则不会发生,因为对于结构,您将对象的实际副本保存到列表中,而不仅仅是引用就像你上课一样。
这是一个例子。
public class A
{
public int Test{ get; set; }
}
代码中的其他一些地方:
List<A> list = new List<A>();
A a = new A();
for( int i = 0; i < 2; i++ )
{
a.Test = i;
list.Add(a);
}
这将以包含对同一A对象的两个引用的列表结束。所以list [0] .Test是1,列表[1] .Test是1.
代码中的其他一些地方:
List<A> list = new List<A>();
for( int i = 0; i < 2; i++ )
{
A a = new A();
a.Test = i;
list.Add(a);
}
这将最终得到一个包含对两个不同A对象的引用的列表。所以list [0] .Test为0,list [1] .Test为1.