我有类属性和值。我不知道如何克隆列表中的项目值。
public class Attribut : ICloneable
{
public Attribut()
{ }
public Attribut(List<Values> value)
{
this.Values = value;
}
public object Clone()
{
return this.MemberwiseClone();
}
//other members
List<Values> values = new List<Values>();y
public List<Values> Values
{
get { return values; }
set { values = value; }
}
}
[Serializable]
public class Values : ICloneable
{
public Values()
{
}
public Values(string name)
{
this.Name = name;
}
public Values(string name, int count)
{
this.Name = name;
this.Count = count;
}
public object Clone()
{
return this.MemberwiseClone();
}
string name;
int count = 0;
public int Count
{
get { return count; }
set { count = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
当我调用此方法时克隆值有问题(attrList)是全局变量)当我将新值添加到列表中时,同样的值也会添加到 attrList 中。
private List<Attribut> getSelectedColumns()
{
List<Attribut> list = new List<Attribut>();
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
list.Add((Attribut)attrList[i].Clone());
for(int j= 0; j < attrList[i].Values.Count;j++)
{
list[j].Values.Add((Values)attrList[i].Values[j].Clone());
}
}
}