一,什么是特性
特性也是一種對象,特殊之處在於其編譯時就存在了,也就是在程序運行之前就存在了。
二,如何定義一個特性
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public sealed class RequiredAttribute:Attribute { public bool Validate(object value) { if (value == null) return true; if (string.IsNullOrEmpty(value.ToString())) return true; if (string.IsNullOrWhiteSpace(value.ToString())) return true; return false; } }
三,特性驗證實體屬性正確性
- 定義特性基類

/// <summary> /// 數據特性驗證的基類 /// </summary> public abstract class AbstractValidateAttribute : Attribute { public abstract bool Validate(object value); }
- 實現NullEmpty特性
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public sealed class NullEmptyAttribute : AbstractValidateAttribute { public override bool Validate(object value) { if (null == value) return true; return string.IsNullOrEmpty(value.ToString()); } }
- 實現Validate擴展方法
1 public static class AttributeExtend 2 { 3 public static void Validate<T>(this T tModel) where T : new() 4 { 5 Type type = tModel.GetType(); 6 foreach (var prop in type.GetProperties()) 7 { 8 if (prop.IsDefined(typeof(AbstractValidateAttribute), true)) 9 { 10 object[] attributeArray = prop.GetCustomAttributes(typeof(AbstractValidateAttribute), true); 11 foreach (AbstractValidateAttribute attribute in attributeArray) 12 { 13 if (attribute.Validate(prop.GetValue(tModel, null))) 14 { 15 //return true;//表示終止 16 throw new Exception(string.Format("{0}的值不可為{1}", prop.Name, prop.GetValue(tModel, null) == null ? "null" : prop.GetValue(tModel, null).ToString())); 17 } 18 } 19 } 20 } 21 //return false; 22 } 23 24 25 }
- 定義實體並使用NullEmpty特性
1 public class Student 2 { 3 public int Id { get; set; } 4 [NullEmpty] 5 public string Name { get; set; } 6 }
- 調用驗證方法
1 try 2 { 3 Student _Student = new Student(); 4 _Student.Validate(); 5 } 6 catch (Exception ex) 7 { 8 Console.WriteLine(ex.Message); 9 } 10 11 Console.ReadKey();
顯示結果:
源碼GitHub: https://github.com/founshi/AttributeDemo