C#中的Attribute验证
一、定义特性
- 定义验证抽象类
public abstract class AbstractValidateAttribute:Attribute
{
//和接口类似,抽象方法只声明方法
public abstract bool Validate(object objValue);
}
- 长度验证特性类
[AttributeUsage(AttributeTargets.Property)]
public class LongAttribute : AbstractValidateAttribute
{
private long _Long = 0;
public LongAttribute(long phoneLength)
{
this._Long = phoneLength;
}
public override bool Validate(object objValue)
{
return objValue != null && objValue.ToString().Length == 11;
}
}
- 非空验证特性类
[AttributeUsage(AttributeTargets.Property)]
public class RequiredAttribute : AbstractValidateAttribute
{
public override bool Validate(object objValue)
{
return objValue != null && !string.IsNullOrWhiteSpace(objValue.ToString());
}
}
- 字符串长度验证类
[AttributeUsage(AttributeTargets.Property)]
public class StringLengthAttribute : AbstractValidateAttribute
{
//字段
private int _Mni=0;
private int _Max = 0;
public StringLengthAttribute(int min,int max)
{
this._Max = max;
this._Mni = min;
}
public override bool Validate(object objValue)
{
return objValue != null
&& objValue.ToString().Length >= this._Mni
&& objValue.ToString().Length <= this._Max;
}
}
- 验证拓展类
public static class AttributeExtend
{
public static bool Validate(this T t)
{
Type type = t.GetType();
foreach (var property in type.GetProperties())//属性上查找
{
if (property.IsDefined(typeof(AbstractValidateAttribute),true))
{
object objValue = property.GetValue(t);
foreach (AbstractValidateAttribute attribute in property.GetCustomAttributes(typeof(AbstractValidateAttribute), true))
{
if (!attribute.Validate(objValue))//如果成功了以后 就继续验证,否则就直接返回
{
return false ;
}
}
}
}
return true;
}
}
-
学生实体类
在学生实体类的属性上,使用特性验证
public class Student
{
public int Id { get; set; }
[Required]
[StringLength(2,3)]
public string StudentName { get; set; }
[Required]
[Long(11)]
public long PoneNumber { get; set; }
}
二、调用验证特性
Student student = new Student()
{
Id = 1,
PoneNumber = 12345678900,
StudentName = "小刚"
};
if (student.Validate())
{
Console.WriteLine("验证成功");
}
else
{
Console.WriteLine("验证失败");
}