特性的使用,校验long 长度

1 特性attribute定义:是一个类,编译时决定,不能使用变量
2 声明和使用attribute,AttributeUsage
3 运行中获取attribute:额外信息 额外操作

4 Remark封装、attribute验证

特性的使用:

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("特性校验成功");
}

------------------------------第3方主动使用特性,特性才有作用,特性本身就一个类-----------------------------

public static void ManagerStudent<T>(T student) where T : Student
{
Console.WriteLine($"{student.Id}_{student.Name}");
student.Study();
student.Answer("123");

Type type = student.GetType();
if (type.IsDefined(typeof(CustomAttribute), true))
{
//type.GetCustomAttribute()
object[] oAttributeArray = type.GetCustomAttributes(typeof(CustomAttribute), true);
foreach (CustomAttribute attribute in oAttributeArray)
{
attribute.Show();
//attribute.Description
}

foreach (var prop in type.GetProperties())
{
if (prop.IsDefined(typeof(CustomAttribute), true))
{
object[] oAttributeArrayProp = prop.GetCustomAttributes(typeof(CustomAttribute), true);
foreach (CustomAttribute attribute in oAttributeArrayProp)
{
attribute.Show();
}
}
}
foreach (var method in type.GetMethods())
{
if (method.IsDefined(typeof(CustomAttribute), true))
{
object[] oAttributeArrayMethod = method.GetCustomAttributes(typeof(CustomAttribute), true);
foreach (CustomAttribute attribute in oAttributeArrayMethod)
{
attribute.Show();
}
}
}

}

原文地址:https://www.cnblogs.com/csj007523/p/14279869.html