gpt4 book ai didi

c# - IEnumerable 属性的 ValidationAttribute

转载 作者:太空宇宙 更新时间:2023-11-03 20:24:57 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com