我有这个用于验证集合的自定义验证属性。我需要调整它以使用 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
工具 ICollection
和 ICollection
工具 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/