c# - 如何使用未知 T 从 ICollection<T> 获取计数

标签 c# .net collections

到目前为止,这是我的代码:

//TODO: Look for a way of handling ICollection<T>

if (value is ICollection)
{
    return CreateResult(validationContext, ((ICollection)value).Count);
}

if (value is IEnumerable)
{
    var enumerator = ((IEnumerable)value).GetEnumerator();
    try
    {
        var count = 0;
        while (enumerator.MoveNext())
            count++;
        return CreateResult(validationContext, count);
    }
    finally
    {
        if (enumerator is IDisposable)
            ((IDisposable)enumerator).Dispose();
    }

}

有没有好的方法可以得到 Count来自 ICollection<T>无需诉诸遍历集合?

最佳答案

没有 ICollection<T> 的封闭类型,您必须诉诸反射来调用 Count 属性。

if (typeof(ICollection<>) == value.GenericTypeDefinition()) {
  var countProp = value.GetType().GetProperty("Count");
  var count = (int)countProp.GetValue(value, null);
}

关于c# - 如何使用未知 T 从 ICollection<T> 获取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8306266/

相关文章:

c# - asp.net mvc url中的双引号

c# - iTextSharp GetFieldPositions 到 SetSimpleColumn

.net - 使用 TypeScript 和 ASP.Net WebApi 进行完整打字

java - PassiveExpiringMap 不会使对象过期

java - 使用 TreeMap 的流返回不连贯的结果

c# - 通用 - 编译器警告 CS0693 或错误

c# - 文件流.读取(...): Will I ever get a nibble rather than byte?

c# - 是否有包含 Dapper.Net SqlBuilder 的 nuget 包?

c# - .NET 中的异步消息传递

Python:为列表中的每个对象添加时间戳