C# List Copy
UserModel 略
List<UserModels> lstUser = new List<UserModels>{...}
Coyp:
var lstUserCopy = new List<UserModels>(lstUser.ToArray());
Test1:
lstUserCoyp.Add(new UserModels{...});
lstUser.length + 1 = lstUserCoyp.length OK!
Test2:
lstUserCoyp[0].Birthday = DateTime.Parse("2014/12/31");
lstUser[0] 发成变化。 ERROR!
结论-----------------------------------------------------------------
var lstUserCopy = new List<UserModels>(lstUser) 如果是值类型可以使用。不适用于引用类型。
List.CopyTo() 方法也是如此,不是深度考备。
CopyTo考备的只是UserModel的值,而UserModel的值都只是UserModel对象的引用。
List深Copy------------------------------------------------------------------
model
[Serializable] public class UserModels:ICloneable { public string UserName { get; set; } public int Age { get; set; } public DateTime Birthday { get; set; } public object Clone() { MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, this); stream.Position = 0; var obj = formatter.Deserialize(stream) as UserModels; return obj; } }
list扩展方法
public static class Extensions { public static IList<T> Clone<T>(this IList<T> listToClone) where T:ICloneable { return listToClone.Select(item => (T)item.Clone()).ToList(); } }
使用
var lstUserCopy = lstUser.Clone();