按值添加对象到列表(不仅仅是引用)

时间:2011-12-29 13:32:53

标签: asp.net .net list

public List<RoleAssignment> lstRoleAssignments1 = new List<RoleAssignment>();
public List<RoleAssignment> lstRoleAssignments2 = new List<RoleAssignment>();


public class RoleAssignment
{
int RoleAssignmentId{get;set;}
}

RoleAssignment objRoleAssign = new RoleAssignment();
objRoleAssign.RoleAssignmentId = 1;

lstRoleAssignments1.Add(objROleAssign);

objRoleAssign.RoleAssignmentId = 2;
lstRoleAssignments2.Add(objROleAssign);

在这两种情况下,这两个列表都有一个对象,属性RoleAssignmentId的值 2

我想要的是lstRoleAssignments1中的RoleAssignmentId是1而lstRoleAssignments2中是2.我不能使用结构,因为我需要使用list作为属性,因此需要在类中实例化它。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

创建RoleAssignment的新实例

RoleAssignment objRoleAssign = new RoleAssignment();
objRoleAssign.RoleAssignmentId = 1;    
lstRoleAssignments1.Add(objROleAssign);

objRoleAssign = new RoleAssignment();
objRoleAssign.RoleAssignmentId = 2;
lstRoleAssignments2.Add(objROleAssign);

lstRoleAssignments1.Add(new RoleAssignment { RoleAssignmentId = 1 });
lstRoleAssignments2.Add(new RoleAssignment { RoleAssignmentId = 2 });