Attribute的妙用

Attribute 類別

本來看到有感覺後想要寫篇blog來紀錄一下心得分享的

結果發現想寫的sample code也早已有人寫過了

那就來整理一下Attribute這東西的使用心得好了

Attribute 類別

本來看到有感覺後想要寫篇blog來紀錄一下心得分享的

結果發現想寫的sample code也早已有人寫過了

那就來整理一下Attribute這東西的使用心得好了

首先Attribute這東西對有在寫.NET的人來說一定不陌生

就拿很好用的LINQ來說好了

就常常會看到

image

這樣的東西,還有WebMethod等等

屬性是什麼呢?

顧名思義就是幫.NET中的東西貼上一個特定的標籤

在MSDN中是這樣解說的

屬性提供的資訊也稱為中繼資料 (Metadata)。應用程式可在執行階段檢查中繼資料,來控制程式處理資料的方式,也可以在執行階段前,利用外部工具,來控制應用程式如何對其本身進行處理或維護

這已經講得很明顯了

應用程式可以在執行階段檢查他,所以也可以順便對被加上某屬性的東西動手腳

AttributeTargets 列舉型別(System)

以上是可以加上屬性的.NET物件

Attrubute怎麼寫可以看Attribute的sample就可以了

但是要怎麼用就好玩了

您可以參考

http://www.dotblogs.com.tw/regionbbs/archive/2009/06/28/use_stackframe.aspx

中的IntegerValidationAttribute跟

http://chuiwenchiu.spaces.live.com/blog/cns!CA5D9227DF9E78E8!1875.entry

這邊的EmbedImageAttribute都是很有用的手法

EmbedImageAttribute這種吸取其他Framework的手法來應用這點也蠻有趣的

另外在MSDN中也有一段我覺得蠻有趣的提示

屬性概觀

您可以使用屬性以任何您能想到的方式來描述您的程式碼,和以具創意的新方式來影響執行階段行為

說真的

.NET的許多功能加以加工加點創意進去真的會讓您coding的過程激發出一些有趣的想法

誰說寫code一定要很呆板又沒有辦法自己加上創意來玩呢?


/// 抓包含的Attribute
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
private static T GetAttributeBy<T>(object source) where T : Attribute {
    T _result = null;
    Attribute[] attrs = Attribute.GetCustomAttributes(source.GetType());
    foreach (Attribute item in attrs) {
        if (item is T) {
            _result = (T)item;
            break;
        }
    }
    return _result;
}

Method


[Obsolete("停用此類別", false)]
public class Car {

}

public class UserProfileAttribute : Attribute {
    string _name = string.Empty;
    public string Name {
        set { _name = value; }
        get { return _name; }
    }
    public UserProfileAttribute(string name) {
        _name = name;
    }
}

Class


ObsoleteAttribute userProfile = GetAttributeBy<ObsoleteAttribute>(car);
if (userProfile != null) {
    Response.Write(String.Format("Message : {0}", userProfile.Message));
} else {
    Response.Write("empty");
}

Try Sample

寫一個小Method來方便以後抓Attribute的作業吧:P

希望能讓更多人對Attribute有感覺