public abstract class AbstractAttribute : Attribute {
public AbstractAttribute()
{
}
public abstract bool Validate(object Value);
}
public class DataLengthAtribute : AbstractAttribute
{
private int _min = 0;
private int _max = 30;
public DataLengthAtribute(int min,int max)
{
_min = min;
_max = max;
}
public override bool Validate(object Value) {
if (Value==null||string.IsNullOrEmpty( Value.ToString()))
{
return false;
}
else
{
return Value.ToString().Length >= _min && Value.ToString().Length <= _max;
}
}
public static class ExtendValidate {
public static bool Validate(object o) {
Type type = o.GetType();
foreach (var item in type.GetProperties())
{
if (item.IsDefined(typeof(AbstractAttribute),true))
{
AbstractAttribute attribute = (AbstractAttribute)item.GetCustomAttribute(typeof(AbstractAttribute),true);
if (!attribute.Validate(item.GetValue(o)))
{
return false;
}
}
}
return true;
}
}
调用样例
public class model {
[DataLengthAtribute(6,70)]
public string kk { set; get; }
}
model m = new model();
m.kk = "1235647";
if (ExtendValidate.Validate(m))
{
Console.WriteLine("验证通过");
}
else
{
Console.WriteLine("验证失败");
}
}