我有这个自定义的验证属性来验证一个集合。我需要对此进行调整以与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()。
有什么想法吗?
发布于 2012-06-20 22:30:14
尝尝这个
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。因此,除了IList之外,IEnumerable将适用于任何设计良好的集合或枚举类型。例如,Dictionary<K,V>不实现IList,但实现了ICollection,因此也实现了IEnumeration。
.NET命名约定规定,属性类名称应始终以" attribute“结尾。因此,您的类应该命名为CollectionHasElementsAttribute。在应用属性时,您可以删除" attribute“部分。
[CollectionHasElements]
public List<string> Names { get; set; }发布于 2015-12-12 21:42:05
列表和复选框列表所需的验证属性
[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; }https://stackoverflow.com/questions/11121702
复制相似问题