【问题标题】:How to create a method that uses and returns generic type?如何创建一个使用并返回泛型类型的方法?
【发布时间】:2012-05-03 22:25:47
【问题描述】:

我正在使用此方法制作对象列表的深层副本:

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;
        }

我的问题是如何更改此方法以接受任何类型的列表并返回该列表的克隆?

另外,请问您的答案的用法是什么!

【问题讨论】:

    标签: c# generics


    【解决方案1】:
    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&lt;&gt;,请参阅我对同一问题的回答,其中包含一组单元测试、错误处理,而且它被实现为易于使用的扩展方法。见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 
    

    【讨论】:

      【解决方案2】:

      将您的原型更改为:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-21
        • 1970-01-01
        • 2023-03-12
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多