c# - 如何创建使用并返回泛型类型的方法?

标签 c# generics

我正在使用此方法制作对象列表的深拷贝:

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/

相关文章:

c# - 编辑现有的 Excel 文件 C# npoi

返回不同类型泛型列表的Java方法

java - 如何用泛型实现枚举?

c# - 获取 ICollection<T> 实现类的类型参数

c# - 需要遍历一个解决方案中的.cs文件,判断是否使用了某个函数

c# - 在 Web API 中上传单个文件

c# - 我无法将对话框发布到 Azure 'TypeError - Cannot read property ' AzureSubscriptionId' 未定义”[Bot Composer Framework]

c# - ExecuteStoredProcedureAsync() 返回不同的结果

java - 如何获取通用列表的类类型?

Java 未经检查的操作转换为泛型