我做了几个假设。
- 集合在静态类中作为静态属性
- 集合继承自 IList
首先你需要自定义属性
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ListCheckAttribute : ValidationAttribute
{
// The name of the class that holds the collection
public Type ContainerType { get; private set; }
// The name of the property holding the list
public string PropertyName { get; private set; }
public ListCheckAttribute(Type ContainerType, String PropertyName)
{
this.ContainerType = ContainerType;
this.PropertyName = PropertyName;
}
public override bool IsValid(object value)
{
var property = ContainerType.GetProperty(this.PropertyName);
var val = property.GetMethod.Invoke(null, null);
var list = (IList)val;
return list.Contains(value);
}
}
public class MyClass
{
[ListCheck(typeof(CollectionClass), "Collection")]
public int NumberToValidate { get; set; }
public MyClass()
{
NumberToValidate = 4;
}
}
现在,当验证处理程序调用 IsValid 时,它会从列表中获取属性并将它们转换为 IList,以便可以完成包含。对于类,他们所要做的就是实现 IEquatable 并实现 Equals 方法,它们也能正常工作。