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<T>(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("验证失败");
}
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16071263.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。