.NET自定义特性:通过封装、继承和多态实现自定义特性的数据校验
public abstract class BaseAttribute:Attribute
{
public abstract bool Validate<T>(T obj);
public virtual string Error { get; set; }
}
class RangeAttribute: BaseAttribute
{
const int min = 0;
const int max = 150;
// public override string Error { get => base.Error; set => base.Error = "长度必须是4~7"; }
public override bool Validate<T>(T obj)
{
double tempValue;
Double.TryParse(obj.ToString(), out tempValue);
if(tempValue <min || tempValue >max)
{
base.Error = $"数据必须大于{min},小于{max}";
return false;
}
return true;
}
}
class