標籤:
屬性(Attribute)是C#程式設計中非常重要的一個技術,應用範圍廣泛,用法靈活多變。本文就以執行個體形式分析了C#中屬性的應用。具體入戲:
一、運用範圍
程式集,模組,類型(類,結構,枚舉,介面,委託),欄位,方法(含構造),方法,參數,方法傳回值,屬性(property),Attribute
[AttributeUsage(AttributeTargets.All)] public class TestAttribute : Attribute { } [TestAttribute]//結構 public struct TestStruct { } [TestAttribute]//枚舉 public enum TestEnum { } [TestAttribute]//類上 public class TestClass { [TestAttribute] public TestClass() { } [TestAttribute]//欄位 private string _testField; [TestAttribute]//屬性 public string TestProperty { get; set; } [TestAttribute]//方法上 [return: TestAttribute]//定義傳回值的寫法 public string TestMethod([TestAttribute] string testParam)//參數上 { throw new NotImplementedException(); } }
這裡我們給出了除了程式集和模組以外的常用的Atrribute的定義。
二、自訂Attribute
為了符合“Common Language Specification(CLS)”的要求,所有的自訂的Attribute都必須繼承System.Attribute。
第一步:自訂一個檢查字串長度的Attribute
[AttributeUsage(AttributeTargets.Property)]public class StringLengthAttribute : Attribute{ private int _maximumLength; public StringLengthAttribute(int maximumLength) { _maximumLength = maximumLength; } public int MaximumLength { get { return _maximumLength; } }}
AttributeUsage這個系統提供的一個Attribute,作用來限定自訂的Attribute範圍,這裡我們只允許這個Attribute運用在Property上,內建一個帶參的構造器,讓外部傳入要求的最大長度。
第二步:建立一個實體類來運行我們自訂的屬性
public class People{ [StringLength(8)] public string Name { get; set; } [StringLength(15)] public string Description { get; set; }}
定義了兩個字串欄位Name和Description, Name要求最大長度為8個,Description要求最大長度為15.
第三步:建立驗證的類
public class ValidationModel{ public void Validate(object obj) { var t = obj.GetType(); //由於我們只在Property設定了Attibute,所以先擷取Property var properties = t.GetProperties(); foreach (var property in properties) { //這裡只做一個stringlength的驗證,這裡如果要做很多驗證,需要好好設計一下,千萬不要用if elseif去連結 //會非常難於維護,類似這樣的開源項目很多,有興趣可以去看源碼。 if (!property.IsDefined(typeof(StringLengthAttribute), false)) continue; var attributes = property.GetCustomAttributes(); foreach (var attribute in attributes) { //這裡的MaximumLength 最好用常量去做 var maxinumLength = (int)attribute.GetType(). GetProperty("MaximumLength"). GetValue(attribute); //擷取屬性的值 var propertyValue = property.GetValue(obj) as string; if (propertyValue == null) throw new Exception("exception info");//這裡可以自訂,也可以用具體系統異常類 if (propertyValue.Length > maxinumLength) throw new Exception(string.Format("屬性{0}的值{1}的長度超過了{2}", property.Name, propertyValue, maxinumLength)); } } }}
這裡用到了反射,因為Attribute一般都會和反射一起使用,這裡驗證了字串長度是否超過所要求的,如果超過了則會拋出異常
private static void Main(string[] args){ var people = new People() { Name = "qweasdzxcasdqweasdzxc", Description = "description" }; try { new ValidationModel().Validate(people); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine();}
C#屬性(Attribute)用法執行個體解析