4
我正在开发一个拥有大量头等集合的代码库。将一个集合转换为另一个集合的通用扩展方法
为了缓解使用这些集合与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>()
或这是不一般可以做的事情?
恐怕没有。 – MarcinJuraszek
为什么你有这么多不同的收藏?这看起来像代码味道给我。 – svick
@svick - 有很多集合,因为它是一个很大的代码库,并且第一类集合比通用对象集合更受欢迎,以便在某处封装基于集合的规则,而不是相对于通用IWhatever定义它们。我不知道这是一个好还是坏的决定,但我知道'var a = Member.Offers.ActiveOffers()'看起来比每次使用.Where()更清洁一点。 –