【发布时间】:2014-02-26 12:43:22
【问题描述】:
在 .NET 通用接口中,ICollection<T> 本身具有 Count 属性。但它不继承任何具有Count 属性的非通用接口。
所以,现在如果你想确定非泛型IEnumerable的数量,你必须检查它是否实现了ICollection,如果没有,你必须使用反射来查找它是否实现了泛型ICollection<X>,因为你不知道通用参数X。
如果ICollection<T> cannot inherit from directly from ICollection,为什么没有另一个只有Count属性的非泛型接口?
这只是糟糕的设计选择吗?
更新:为了让问题更清楚,我在我当前的实现中演示了这个问题:
static int? FastCountOrZero(this IEnumerable items)
{
if (items == null)
return 0;
var collection = items as ICollection;
if (collection != null)
return collection.Count;
var source = items as IQueryable;
if (source != null)
return QueryableEx.Count(source);
// TODO process generic ICollection<> - I think it is not possible without using reflection
return items.Cast<object>().Count();
}
【问题讨论】:
-
IEnumerable 可能是无限的,所以 Count 不适用。
-
为什么不使用
coll.Count()让.NET 确定它是否具有Count属性? -
@TN.: 那么你仍然可以使用
enumerable.Cast<object>().Count(),因为它仍然实现ICollection,因此Enumerable.Count将使用Count属性而不是枚举所有。 -
@TN.:如果对象实现了
ICollection,则可以。例如:IEnumerable enumerable = new List<string>(); enumerable = enumerable.Cast<object>(); int count = enumerable.Cast<object>().Count()。这仍将在后台使用Count属性。 -
@TimSchmelter 但是我可以通过转换为
ICollection直接解决这个问题。它对ICollection<T>没有帮助。这是我的问题。 (因为ICollection<T>不继承非泛型ICollection。)
标签: c# .net generics collections