到目前为止,这是我的代码:
//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/