我嘗試複製列表,但是當我更改第二個列表時,第一個列表隨第二個列表而更改。如何複製列表而不影響第一個列表
我的模型類:
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