我尝试复制列表,但是当我更改第二个列表时,第一个列表随第二个列表而更改。如何复制列表而不影响第一个列表
我的模型类:
public class urunler : ICloneable
{
public int id { get; set; }
public string icerik { get; set; }
}
扩展类:
using System.Collections.Generic;
using System;
using System.Linq;
namespace Extensions
{
public static class Extensions {
public static IList<T> Clone<T>(this IList<T> SourceList) where T: ICloneable
{
return SourceList.Select(item => (T)item.Clone()).ToList();
}
}
}
BLL类:
using System.Linq;
using Extensions;
public class bll
{
public void examp
{
List<urunler> L1 = new List<urunler>();
urunler U = new urunler();
U.icerik="old";
L1.Add(U);
List<urunler> L2 = L1.Clone();
L2[0].icerik="new";
MessageBox.show(L1[0].icerik);
MessageBox.show(L2[0].icerik);
//
}
}
错误:
error CS0535: `urunler' does not implement interface member `System.ICloneable.Clone()'
然后我尝试改变模型类:
public class urunler : ICloneable
{
#region ICloneable implementation
IList<urunler> ICloneable.Clone()
{
throw new NotImplementedException();
}
#endregion
public int id { get; set; }
public string icerik { get; set; }
}
错误:
error CS0539: `System.ICloneable.Clone' in explicit interface declaration is not a member of interface
它的工作原理这个时候,我改变了我的模型类
public class urunler : ICloneable
{
public object Clone()
{
return this.MemberwiseClone();
}
public int id { get; set; }
public string icerik { get; set; }
}
而且改变了我的BLL类:
//before:
//List<urunler> L2 = L1.Clone();
//after:
List<urunler> L2 = L1.Clone().toList();
您正在复制引用。使用克隆方法或CopyTo方法或ctor与旧列表列表创建基于原始的依赖列表。 – icbytes
已回答多次http://stackoverflow.com/a/222623/125740 – Yahya
请做好您的研究。 – Yahya