namespace AttributeTest
{
//使用特性封装提供额外行为Validate验证
class Program
{
static void Main(string[] args)
{
Student student = new Student()
{
Name = "123",
QQ = 20000
};
Console.WriteLine(student.Validate());
Console.ReadLine();
}
}
}
namespace AttributeTest
{
//学生实体类
public class Student
{
[Required]
public string Name { get; set; }
[Validate(10000,99999)]
public long QQ { get; set; }
}
}
namespace AttributeTest
{
//特性attribute;就是一个类,直接继承/间接继承自Attribute父类
//约定俗成用Attribute结尾,标记时就可以省略掉
public abstract class AbstractValidateAttribute : Attribute
{
public abstract bool Validate(object value);
}
}
//验证不可为null或者空
public class RequiredAttribute : AbstractValidateAttribute
{
public override bool Validate(object value)
{
return value != null && value.ToString() != "";
}
}
//验证是否在范围内
[AttributeUsage(AttributeTargets.Property)]
public class ValidateAttribute : AbstractValidateAttribute
{
private long _Min;
private long _Max;
public ValidateAttribute(long min, long max)
{
_Max = max;
_Min = min;
}
public override bool Validate(object value)
{
return value != null && long.TryParse(value.ToString(), out long Lvalue) && Lvalue > _Min && Lvalue < _Max;
}
}
public static class AttributeExtend
{
//从类型 属性 方法 都可以获取特性实例,要求先IsDefined检测 再获取(实例化)
public static bool Validate<T>(this T t)
{
Type type = t.GetType();
foreach (PropertyInfo item in type.GetProperties())
{
if (item.IsDefined(typeof(AbstractValidateAttribute), true))
{
object ovalue = item.GetValue(t);
AbstractValidateAttribute attribute = (AbstractValidateAttribute)item.GetCustomAttribute(typeof(AbstractValidateAttribute), true);
if (!attribute.Validate(ovalue))
return false;
}
}
return true;
}
}