特性的使用:
1.定义T的扩展方法:Validate
public static bool Validate<T>(this T t)
{
Type type = t.GetType();
foreach (var prop in type.GetProperties())
{
if (prop.IsDefined(typeof(AbstractValidateAttribute), true))
{
object oValue = prop.GetValue(t);
foreach (AbstractValidateAttribute attribute in prop.GetCustomAttributes(typeof(AbstractValidateAttribute), true))
{
if (!attribute.Validate(oValue))
return false;
}
}
}
return true;
}
2. 定义校验基类AbstractValidateAttribute
和需要校验的long类型:LongAttribute
public abstract class AbstractValidateAttribute : Attribute
{
public abstract bool Validate(object oValue);
}
定义long校验类
[AttributeUsage(AttributeTargets.Property)]
public class LongAttribute : AbstractValidateAttribute
{
private long _Min = 0;
private long _Max = 0;
public LongAttribute(long min, long max)
{
this._Min = min;
this._Max = max;
}
public override bool Validate(object oValue)
{
return oValue != null
&& long.TryParse(oValue.ToString(), out long lValue)
&& lValue >= this._Min
&& lValue <= this._Max;
}
}
4.model 属性的校验:
public class Student
{
[Long(10000, 999999999999)]
public long QQ { get; set; }
}
Student student = new Student()
if (student.Validate())
{
Console.WriteLine("特性校验成功");
}
原文:https://www.cnblogs.com/csj007523/p/14279869.html