我在一个代码库中工作,该代码库有很多第一类集合。
为了便于在LINQ中使用这些集合,每个集合都有一个扩展方法,如下所示:
public static class CustomCollectionExtensions
{
public static CustomCollection ToCustomCollection(this IEnumerable<CustomItem> enumerable)
{
return new CustomCollection(enumerable);
}
}
随附的构造函数:
public class CustomCollection : List<CustomItem>
{
public CustomCollection(IEnumerable<CustomItem> enumerable) : base(enumerable) { }
}
这最终成了一堆样板,所以我试图写一个通用的IEnumerable<U>.To<T>()
,这样我们就不必继续生成这些特定的ToXCollection()方法。
我得到了:
public static class GenericCollectionExtensions
{
public static T To<T, U>(this IEnumerable<U> enumerable) where T : ICollection<U>, new()
{
T collection = new T();
foreach (U u in enumerable)
{
collection.Add(u);
}
return collection;
}
}
必须像customCollectionInstance.OrderBy(i => i.Property).To<CustomCollection, CustomItem>()
有没有办法避免必须指定CustomItem
类型,以便我们可以使用customCollectionInstance.OrderBy(i => i.Property).To<CustomCollection>()
或者这不是一般可以完成的事情吗?
答案 0 :(得分:5)
接近你想要的东西:
public static class GenericCollectionExtensions
{
public sealed class CollectionConverter<TItem>
{
private readonly IEnumerable<TItem> _source;
public CollectionConverter(IEnumerable<TItem> source)
{
_source = source;
}
public TCollection To<TCollection>()
where TCollection : ICollection<TItem>, new()
{
var collection = new TCollection();
foreach(var item in _source)
{
collection.Add(item);
}
return collection;
}
}
public static CollectionConverter<T> Convert<T>(this IEnumerable<T> sequence)
{
return new CollectionConverter<T>(sequence);
}
}
用法:
customCollectionInstance.OrderBy(i => i.Property).Convert().To<CustomCollection>();