我正在使用此方法制作对象列表的深拷贝:
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;
}
我的问题是如何更改此方法以接受任何类型的列表并返回该列表的克隆?
另外,请问您的答案的用法是什么样的!
最佳答案
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
显然你可以在没有throwInCaseOfError
的情况下创建更简单的重载参数:
public static TObject DeepCopy<TObject>(this TObject instance)
where TObject : class
关于c# - 如何创建使用并返回泛型类型的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10278341/