我正在使用此方法制作对象列表的深层副本:
public static List<TransformColumn> Clone(List<TransformColumn> original)
{
List<TransformColumn> returnValue;
using (var stream = new System.IO.MemoryStream())
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, original); //serialize to stream
stream.Position = 0;
//deserialize from stream.
returnValue = binaryFormatter.Deserialize(stream) as List<TransformColumn>;
}
return returnValue;
}
我的问题是如何更改此方法以接受任何类型的列表并重新命名该列表的克隆?
另外,请问您的答案的用法是什么样的!
答案 0 :(得分:4)
public static List<TEntity> Clone<TEntity>(List<TEntity> original)
{
List<TEntity> returnValue = null;
using (var stream = new System.IO.MemoryStream())
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
//serialize to stream
binaryFormatter.Serialize(stream, original);
stream.Position = 0;
//deserialize from stream.
returnValue = binaryFormatter.Deserialize(stream) as List<TEntity>;
}
return returnValue;
}
您可以通过允许任何类型List<>
使您的方法更加通用,通过一组单元测试,错误处理查看我对同一问题的答案,同时它也可以作为扩展方法实现使用。见This StackOverflow post
方法签名是:
public static TObject DeepCopy<TObject>(
this TObject instance,
bool throwInCaseOfError)
where TObject : class
Ans显然你可以在没有throwInCaseOfError
参数的情况下创建更简单的重载:
public static TObject DeepCopy<TObject>(this TObject instance)
where TObject : class
答案 1 :(得分:3)
将原型更改为:
public static List<T> Clone<T>(List<T> original)
将对象反序列化为的行:
returnValue = binaryFormatter.Deserialize(stream) as List<T>;
有关详细信息,请参阅MSDN上的这篇文章:http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.100).aspx