【问题标题】:Can the data type for a generic List<T> be implied?可以隐含泛型 List<T> 的数据类型吗?
【发布时间】:2011-06-18 19:08:37
【问题描述】:

是否有隐含的方式告诉泛型集合使用传入的IEnumerable&lt;T&gt; 数据的Type

假设可以传入任何类型,因为它可能已被隐藏,例如,通过 IQueryable 并且可能包含匿名类型。

var enumerableThings = //... enumerable<T> obtained from somewhere.

点是T是未知的。

我想创建一个List&lt;T&gt;的主要类型的可枚举事物:

var listOfThoseThings = new List<???>(enumerableThings);

C#/.NET 中有许多有趣的机制。找到执行这项任务的能力,我不会感到惊讶。但是目前一种简洁的方式避开了我。

【问题讨论】:

    标签: .net collections c#-4.0 ienumerable


    【解决方案1】:

    只是为了扩展 SLaks 的(正确)答案。

    当您调用ToList 时,这就是调用泛型方法Enumerable.ToList&lt;T&gt;(IEnumerable&lt;T&gt; source)。然后编译器以正常方式使用泛型类型推断来计算出T

    请注意,目前虽然有对ToListToDictionaryToArray 的调用,但没有对HashSet 的等效调用。不过写起来很容易:

    public static class MoreExtensions
    {
        public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
        {
            return new HashSet<T>(source);
        }
    
        public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source,
            IEqualityComparer<T> comparer)
        {
            return new HashSet<T>(source, comparer);
        }
    }
    

    这样做是唯一构造具有类型参数的泛型类型实例的方法,该类型参数是匿名类型,缺少泛型。这是一项好工作,很容易:)

    【讨论】:

    • 这个细节是无价的。谢谢。
    【解决方案2】:
    static List<T> GetList<T>(IEnumerable<T> enumerableThings)
    {
       var listOfThoseThings = new List<T>(enumerableThings);
       return listOfThoseThings;
    }
    

    【讨论】:

      【解决方案3】:

      没有办法直接做到这一点,但是可以通过方法类型推断间接做到这一点

      public static List<T> CreateList<T>(IEnumerable<T> enumerableThings)
      {
        return new List<T>(enumerableThings);
      }
      
      var listOfThoseThings = CreateList(enumerableThings);
      

      【讨论】:

        【解决方案4】:

        这就是ToList() extension method 存在的原因。

        var listOfThoseThings = enumerableThings.ToList();
        

        List&lt;T&gt; 构造函数不同,它可以使用类型推断来隐式指定泛型参数。

        【讨论】:

        • 这当然会在调用时枚举 IEnumerable,如果您的枚举是 linq-sql 或任何其他长时间运行的集合,这可能会产生影响。
        • @asawyer:任何List&lt;T&gt; 都是如此,无论您如何创建它。
        • 是的,只是为@JohnK 注意到它。不愿意发现他没有意识到这一点,最终在一个函数或其他东西中枚举了一个 linq to sql 查询十几次:)
        • 已经通过 LINQ to SQheLL。 :) 在开始之前阅读一下它是值得的。
        猜你喜欢
        • 2011-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多