.Net Attribute詳解(上)-Attribute本質以及一個簡單示例
Attribute的直接翻譯是屬性,這和Property容易產生混淆,所以一般翻譯成特性加以區分。Attribute常常的表現形式就是[AttributeName], 隨意地添加在class, method的頭上,然後就能夠產生各種各樣奇特的效果和行為。比如關於序列化的標簽[Serializable]用來指定一個實體類可以序列化。[NonSerialized]可以用來指定某些屬性不包含在序列化中。
一, Attribute本質是什麽?
Attribute類似於標簽, 可以為類,方法,結構體,屬性,委托等貼上標簽,在以後的實際執行時候,根據不同的標簽做不同的處理。拿類做個比方,如果把一個類看做一個人的話,它有自己的名字Person, 有自己的屬性Hand, Foot等,有自己的功能Walk(), Sleep()等,那麽加在類上的Attribute就好像是給類這個人穿上的一件外衣。如果我們看到他穿的不同制服,就知道這個人是什麽職業,是一個警察,空姐還是快遞。
拿上面的所舉例的序列化標簽[NonSerialized]來說,他就給屬性穿上一件外衣,外衣上寫著“不要序列化我”,這樣在執行具體的序列化的過程中,當序列化操作發現了披著這個外衣對的屬性,就會跳過。
二, Attribute的具象
對於Attribute的具體的代碼呈現,它有這些特點:
1. Attribute是一個類
自定義的Attribute是一個類,而且必須繼承自System.Attribute.
2. Attribute的名字
Attribute類名一般以Attribute結尾, 但是在具體使用時候,可以省去Attribute。加入定義了一個HelperAttribute, 具體使用的時候,可以這樣寫[Helper].
3. Attribute的使用範圍
Attribute類在定義的時候,可以指定這個Attribute的應用範圍,AttributeTargets枚舉就列出了可以指定的範圍,可以是class, field……
[AttributeUsage(AttributeTargets.All)] public class AcronymAttribute : Attribute { }
三, 一個自定義Attribute例子
1. 自定義BlockAttribute
假設有個過濾不當言論的需求,我們可以通過自定義的BlockAttribute為不同類型的人套上外衣,凡是貼上BlockAttribute的人,我們就不允許他發言。
[AttributeUsage(AttributeTargets.Class)]//指定Attribute的使用範圍,只能在class級別使用 public class BlockAttribute : Attribute { public Level Level { get; set; } public BlockAttribute(Level level)//在實例化的時候,就指定Block是Yes還是No { Level = level; } } public enum Level { NO, Yes }
2. 使用Attribute
接著我們把它使用在我們的GovermentSay類上,它的級別自然是Yes
[Block(Level.Yes)] public class GovermentSay : ISay { public string Say() { return "Our country is the most democratic country"; } }
把BlockAttribute用在PeopleSay類上,級別是No
[Block(Level.NO)] public class PeopleSay : ISay { public string Say() { return "We need rights"; } }
3. Attribute的過濾
接著是我們ThePress類,它的主要作用,就是根據BlockAttribute不同,區別對待。因為它們被BlockAttribute貼上了不同的標簽,所以非常容易區分它們。
public class ThePress { public static void Print(ISay say) { System.Reflection.MemberInfo info = say.GetType(); BlockAttribute att= (BlockAttribute)Attribute.GetCustomAttribute(info, typeof(BlockAttribute)); if (att.Level == Level.Yes)//如果標簽是Yes Console.WriteLine(say.GetType().ToString() + ": " + say.Say()); else//如果是No Console.WriteLine(say.GetType().ToString() + ": " + "I Love the country!"); } }
上面就是一個完整的Attribute使用的例子。
四,總結
Attribute使用,一共分三個步驟,Attribute的定義, Attribute的使用(貼標簽), Attribute的讀取和使用(根據標簽做不同處理)
最後,附上本文相關源代碼。 AttributeDemo.zip
.Net Attribute詳解(上)-Attribute本質以及一個簡單示例