c# - IEnumerable 属性的 ValidationAttribute

标签 c# ienumerable

我有这个用于验证集合的自定义验证属性。我需要调整它以使用 IEnumerable。我尝试使该属性成为通用属性,但您不能拥有通用属性。

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class CollectionHasElements : System.ComponentModel.DataAnnotations.ValidationAttribute 
{
     public override bool IsValid(object value)
     {
         if (value != null && value is IList)
         {
             return ((IList)value).Count > 0;
         }
         return false;
     }
}

我无法将它转换为 IEnumerable,以便我可以检查它的 count() 或 any()。

有什么想法吗?

最佳答案

试试这个

var collection = value as ICollection;
if (collection != null) {
    return collection.Count > 0;
}

var enumerable = value as IEnumerable;
if (enumerable != null) {
    return enumerable.GetEnumerator().MoveNext();
}


return false;

或者,自从 C# 7.0 开始使用模式匹配:

if (value is ICollection collection) {
    return collection.Count > 0;
}
if (value is IEnumerable enumerable) {
    return enumerable.GetEnumerator().MoveNext();
}
return false;

注意:测试ICollection.Count比获取枚举器并开始枚举枚举器更有效。因此我尝试使用 Count属性(property)尽可能。然而,第二个测试将单独工作,因为集合总是实现 IEnumerable .

继承层次结构如下:IEnumerable > ICollection > IList . IList工具 ICollectionICollection工具 IEnumerable .因此IEnumerable适用于任何设计良好的集合或枚举类型,但不适用于 IList .例如Dictionary<K,V>不执行 IList但是ICollection因此也是IEnumeration .


.NET 命名约定规定属性类名称应始终以“Attribute”结尾。因此,您的类(class)应命名为 CollectionHasElementsAttribute .应用属性时,您可以删除“属性”部分。

[CollectionHasElements]
public List<string> Names { get; set; }

关于c# - IEnumerable 属性的 ValidationAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11121702/

相关文章:

c# - 我怎样才能改变比较两个图像的方法更快?

c# - ViewModel 可以具有 IEnumerable<> 类型的属性而不是 Array

c# - 来自枚举的 Swagger 预定义返回类型值

c# - visual studio 2017 启动有/无调试性能差异

c# - 正则表达式的字符类和否定

c# - 您将如何实现 IEnumerator 接口(interface)?

c# - IEnumerable/Enumerable with Double/Int;初学者

c# - 跨多林环境从域本地组获取所有成员

linq - 如何在不运行它们的情况下合并两个 Linq IEnumerable<T> 查询?

c# - IEnumerable<T> 如何在后台工作