Reflecting of Attribute via IL in CLR探索

來源:互聯網
上載者:User
關於Attribute的詳細知識,我就不多說了.大家可以參考dudu和anytao的一個系列裡面的介紹,比較經典的探討了Attribute的一些產生和運行機制.
在這裡,我只想從幾個側面來探討下CLR環境下的Attribute.

首先,我們來看一個Reflecting in Attribute的例子:

using System;
using System.Reflection;

public class AttributesReflectingonAttributes
{
    public static void Main()
    {
        Type type = typeof(Complex);
        foreach (CodeReviewAttribute att in
                type.GetCustomAttributes(typeof(CodeReviewAttribute), false))
        {
            Console.WriteLine("Reviewer: {0}", att.Reviewer);
            Console.WriteLine("Date: {0}", att.Date);
            Console.WriteLine("Comment: {0}", att.Comment);
        }
    }
}

[AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
public class CodeReviewAttribute: System.Attribute
{
    public CodeReviewAttribute(string reviewer, string date)
    {
        this.reviewer = reviewer;
        this.date = date;
    }
    public string Comment
    {
        get
        {
            return(comment);
        }
        set
        {
            comment = value;
        }
    }
    public string Date
    {
        get
        {
            return(date);
        }
    }
    public string Reviewer
    {
        get
        {
            return(reviewer);
        }
    }
    string reviewer;
    string date;
    string comment;
}

[CodeReview("AA", "01-12-2000", Comment="Joe' Code")]
[CodeReview("BB", "01-01-2000", Comment="Revisit this section")]
class Complex
{
}


這樣,我們在這個例子中得到的輸出結果是把Complex類的CodeReview這個Attribute裡面的參數給輸出來了.

System的Type這個類中的GetCustomAttributes方法,在衍生類別中被重寫的時候,返回由System.Type表示的自訂屬性的數組.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.