特性是一种辅助代码的一种类,在很大程度上可以帮助我们实现很多相关的特性和功能例如:当数据库和实体类名称不一样时就可以使用特性来解决这种问题,也还可以使用特性来验证数据的正确性从而达到数据的验证校验
简单的来说特性也是一种类 并继承Attribute的一个类通过反编译工具我们可以看出
1 [AttributeUsage(AttributeTargets.Method|AttributeTargets.Class)]//表示可以标注在类和方法上面 2 public class YZMColumnAttribute : Attribute 3 { 4 5 private string _Name = null; 6 public YZMColumnAttribute(string name) 7 { 8 this._Name = name; 9 } 10 public string GetYZMColumnName() 11 { 12 return this._Name; 13 } 14 15 }
获取特性中的值就要是使用类型中使用到Type的类型去获取属性中的值下面我示例
1 public static bool ValiData<T>(this T t) 2 { 3 Type type = t.GetType(); 4 5 foreach (var prop in type.GetProperties())//遍历获取方法内所用的属性成员 6 { 7 if (prop.IsDefined(typeof(ModelReAttribute), true))//判断属性成员中是否有此特性包括继承过来的特性 8 { 9 object value = prop.GetValue(t); 10 foreach (ModelReAttribute attribute in prop.GetCustomAttributes(typeof(ModelReAttribute),true))//实例特性 11 { 12 if (!(attribute.ValiData(value)))//获取特性中的值 13 { 14 return false; 15 } 16 } 17 } 18 //获取特性中的名称 19 if (prop.IsDefined(typeof(YZMColumnAttribute), true)) 20 { 21 object value = prop.GetValue(t); 22 foreach (YZMColumnAttribute attribute in prop.GetCustomAttributes(typeof(YZMColumnAttribute), true)) 23 { 24 var s = attribute.GetYZMColumnName(); 25 26 return false; 27 } 28 } 29 } 30 return true; 31 }
刚刚的方法中获取到了特性的值但是用作判断很是很麻烦于是我们可以将所有的特性全部继承到一个特性性下,从而遍历一个特性就OK
1 namespace YZMFramework.ValiData 2 { 3 public abstract class ModelReAttribute:Attribute 4 { 5 public abstract bool ValiData(object obj); 6 } 7 } 8 9 10 public class YZMRequiredattribute: ModelReAttribute//继承 11 { 12 public override bool ValiData(object obj) 13 { 14 if (string.IsNullOrWhiteSpace(obj.ToString())) 15 { 16 return false; 17 } 18 else { 19 return true; 20 } 21 } 22 } 23 24 25 public class YZMLongAttribute : ValiData.ModelReAttribute//继承 26 { 27 private long _Max = 0; 28 private long _Min = 0; 29 public YZMLongAttribute(long Min, long Max) 30 { 31 this._Min = Min; 32 this._Max = Max; 33 } 34 public override bool ValiData( object obj) 35 { 36 if ( 37 string.IsNullOrWhiteSpace(obj.ToString()) 38 && long.TryParse(obj.ToString(),out long OValues) 39 && OValues>= this._Max 40 && OValues < this._Min 41 ) 42 { 43 return false; 44 45 } 46 return true; 47 } 48 } 49 50 51 52 53 foreach (var prop in type.GetProperties()) 54 { 55 if (prop.IsDefined(typeof(ModelReAttribute), true))//遍历父类就OK,继承必须为True 56 { 57 object value = prop.GetValue(t); 58 foreach (ModelReAttribute attribute in prop.GetCustomAttributes(typeof(ModelReAttribute),true)) 59 { 60 if (!(attribute.ValiData(value))) 61 { 62 return false; 63 } 64 } 65 }