我有这个自定义验证属性来验证集合。我需要调整它以使用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()。
有什么想法吗?
答案 0 :(得分:5)
试试这个
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;
注意:测试ICollection.Count
比获取枚举数并开始枚举枚举数更有效。因此,我尽可能尝试使用Count
属性。但是,第二个测试可以单独使用,因为集合总是实现IEnumerable
。
继承层次结构如下:IEnumerable > ICollection > IList
。 IList
实施ICollection
和ICollection
实施IEnumerable
。因此,IEnumerable
适用于任何精心设计的集合或枚举类型,但不适用于IList
。例如,Dictionary<K,V>
未实现IList
但ICollection
,因此也IEnumeration
。
.NET命名约定表明属性类名称应始终以“Attribute”结尾。因此,您的班级应命名为CollectionHasElementsAttribute
。应用属性时,您可以删除“属性”部分。
[CollectionHasElements]
public List<string> Names { get; set; }
答案 1 :(得分:0)
列表和复选框列表
所需的验证属性[AttributeUsage(AttributeTargets.Property)]
public sealed class CustomListRequiredAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
var list = value as IEnumerable;
return list != null && list.GetEnumerator().MoveNext();
}
}
如果您有复选框列表
[AttributeUsage(AttributeTargets.Property)]
public sealed class CustomCheckBoxListRequiredAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
bool result = false;
var list = value as IEnumerable<CheckBoxViewModel>;
if (list != null && list.GetEnumerator().MoveNext())
{
foreach (var item in list)
{
if (item.Checked)
{
result = true;
break;
}
}
}
return result;
}
}
这是我的视图模型
public class CheckBoxViewModel
{
public string Name { get; set; }
public bool Checked { get; set; }
}
用法
[CustomListRequiredAttribute(ErrorMessage = "Required.")]
public IEnumerable<YourClass> YourClassList { get; set; }
[CustomCheckBoxListRequiredAttribute(ErrorMessage = "Required.")]
public IEnumerable<CheckBoxViewModel> CheckBoxRequiredList { get; set; }