共用方式為


使用反映存取屬性

您可以定義自訂屬性並將它們放在原始程式碼的事實,對於擷取並處理該項資訊並沒有什麼幫助。 使用反射,即可擷取已使用自訂屬性所定義的資訊。 重要方法是 GetCustomAttributes,這會傳回為來源程式碼屬性的執行階段對等項目的物件陣列。 這個方法有多個多載版本。 如需詳細資訊,請參閱Attribute

屬性規格,例如︰

[Author("P. Ackerman", Version = 1.1)]
class SampleClass { }

在概念上相當於下列程式碼:

var anonymousAuthorObject = new Author("P. Ackerman")
{
    Version = 1.1
};

不過,程式碼會等到查詢 SampleClass 的屬性之後才會執行。 在 SampleClass 上呼叫 GetCustomAttributes 會導致建構和初始化 Author 物件。 如果類別有其他屬性,則以類似的方式建構其他屬性物件。 GetCustomAttributes 接著會傳回 Author 物件以及陣列中的任何其他屬性物件。 您接著可以逐一查看這個陣列、根據每個陣列項目的類型來決定已套用的屬性,以及從屬性物件擷取資訊。

以下是完整範例。 定義、套用至數個實體並透過反射來擷取自訂屬性。

// Multiuse attribute.
[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct,
                       AllowMultiple = true)  // Multiuse attribute.
]
public class AuthorAttribute : System.Attribute
{
    string Name;
    public double Version;

    public AuthorAttribute(string name)
    {
        Name = name;

        // Default value.
        Version = 1.0;
    }

    public string GetName() => Name;
}

// Class with the Author attribute.
[Author("P. Ackerman")]
public class FirstClass
{
    // ...
}

// Class without the Author attribute.
public class SecondClass
{
    // ...
}

// Class with multiple Author attributes.
[Author("P. Ackerman"), Author("R. Koch", Version = 2.0)]
public class ThirdClass
{
    // ...
}

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

    private static void PrintAuthorInfo(System.Type t)
    {
        System.Console.WriteLine($"Author information for {t}");

        // Using reflection.
        System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // Reflection.

        // Displaying output.
        foreach (System.Attribute attr in attrs)
        {
            if (attr is AuthorAttribute a)
            {
                System.Console.WriteLine($"   {a.GetName()}, version {a.Version:f}");
            }
        }
    }
}
/* Output:
    Author information for FirstClass
       P. Ackerman, version 1.00
    Author information for SecondClass
    Author information for ThirdClass
       R. Koch, version 2.00
       P. Ackerman, version 1.00
*/

另請參閱