使用反射訪問屬性【MSDN】

來源:互聯網
上載者:User

如果沒有檢索自訂屬性的資訊和對其進行操作的方法,則定義自訂屬性並將其放置在原始碼中就沒有意義。C# 具有一個反射系統,可用來檢索用自訂屬性定義的資訊。主要方法是 GetCustomAttributes,它返回對象數組,這些對象在運行時等效於原始碼屬性。此方法具有多個重載版本。

屬性規範,如:

Code
[Author("H. Ackerman", version = 1.1)]
class SampleClass

在概念上等效於:

Code
Author anonymousAuthorObject = new Author("H. Ackerman");
anonymousAuthorObject.version = 1.1;

 

但是,直到查詢 SampleClass 以擷取屬性時才會執行此代碼。對 SampleClass 調用 GetCustomAttributes 會導致按上述方式構造並初始化一個 Author 對象。如果類還有其他屬性,則其他屬性對象的以類似方式構造。然後 GetCustomAttributes 返回 Author 對象和數組中的任何其他屬性對象。之後就可以對此數組進行迭代,確定根據每個數組元素的類型所應用的屬性,並從屬性對象中提取資訊。

樣本

下面是一個完整的樣本。定義一個自訂屬性,將其應用於若干實體並通過反射進行檢索。

Code
[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct,
                       AllowMultiple = true)  // multiuse attribute
]
public class Author : System.Attribute
{
    string name;
    public double version;

    public Author(string name)
    {
        this.name = name;
        version = 1.0;  // Default value
    }

    public string GetName()
    {
        return name;
    }
}

[Author("H. Ackerman")]
private class FirstClass
{
    // 
}

// No Author attribute
private class SecondClass
{
    // 
}

[Author("H. Ackerman"), Author("M. Knott", version = 2.0)]
private class ThirdClass
{
    // 
}

class TestAuthorAttribute
{
    static void Main()
    {
        PrintAuthorInfo(typeof(FirstClass));
        PrintAuthorInfo(typeof(SecondClass));
        PrintAuthorInfo(typeof(ThirdClass));
    }

    private static void PrintAuthorInfo(System.Type t)
    {
        System.Console.WriteLine("Author information for {0}", t);
        System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection

        foreach (System.Attribute attr in attrs)
        {
            if (attr is Author)
            {
                Author a = (Author)attr;
                System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
            }
        }
    }
}

 

輸出

Author information for FirstClass

H. Ackerman, version 1.00

Author information for SecondClass

Author information for ThirdClass

H. Ackerman, version 1.00

M. Knott, version 2.00

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.