特性
一…特性的使用场景:
框架中,类上面,方法上面,属性上面字段上面,程序集上面,参数上面
二.特性的本质:
一个继承自Attribute类的类。
三.特性的简单的定义,使用以及查找:
定义:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class TestAttribute : Attribute
{
public string TargetVal;
public TestAttribute(string targetVal)
{
TargetVal = targetVal;
}
}
查找:通过反射
public string GetCustomerAttr<T>(T model) where T : class
{
Type type = typeof(T);
if (type.IsDefined(typeof(TestAttribute), true))
{
var attrs = type.GetCustomAttributes(typeof(TestAttribute), true);
return ((TestAttribute)attrs[0]).TargetVal;
}
else
{
return type.Name;
}
}
简单的应用:
先定义一个抽象的特性用于我们的后面的实现验证功能使用
public abstract class CommonAttribute:Attribute
{
public abstract bool isValidatePaas(Object DataVal);
}
再写一个具体的验证类进行实现抽象方法
public class StrinfgLengthAttribute : CommonAttribute
{
public int maxVal;
public int minVal;
public StrinfgLengthAttribute(int max, int min)
{
maxVal = max;
minVal = min;
}
public override bool isValidatePaas(object DataVal)
{
return DataVal.ToString().Length < maxVal && DataVal.ToString().Length < minVal;
}
}
再写一个方法进行其他的验证方法的实现:
public class EmailAttribute : CommonAttribute
{
public override bool isValidatePaas(object DataVal)
{
Regex regex = new Regex( @"/\w[-\w.+] *@([A - Za - z0 - 9][-A - Za - z0 - 9] +\.) +[A - Za - z]{ 2,14}/");
return regex.IsMatch(DataVal.ToString());
}
}
再写一个通用的调用特性方法:
public class CustomerAttr
{
public static bool Volidate<T>(T model)
{
PropertyInfo[] pros = model.GetType().GetProperties();
foreach (var pro in pros)
{
if (pro.IsDefined(typeof(CommonAttribute), true))
{
var attrs = pro.GetCustomAttributes(typeof(CommonAttribute), true);
foreach (var item in attrs)
{
CommonAttribute commonAttribute = item as CommonAttribute;
if (!commonAttribute.isValidatePaas(pro.GetValue(model)))
{
return false;
}
}
}
}
return true;
}
}
在写一个实体类使用特性:
public class Student
{
[StrinfgLength(50,6)]
public string name;
[Email]
public string Email;
}
这样在我们进行实体的创建的时候只需要调用这个方法进行验证将实体传进去即可。
这样我们就简单的实现了一个特性的基本使用