CustomAttribute 結構

定義

提供自訂屬性的相關資訊。

public value class CustomAttribute
public struct CustomAttribute
public readonly struct CustomAttribute
type CustomAttribute = struct
Public Structure CustomAttribute
繼承
CustomAttribute

範例

此範例示範如何列印套用至類型定義的所有自訂屬性:

class MyAttribute : Attribute
{
    public int X { get; set; }
}

[My(X = 1)]
class ExampleType1 { }

[My(X = 2)]
class ExampleType2 { }

static void PrintCustomAttributes(MetadataReader mr, TypeDefinition t)
{
    // Enumerate custom attributes on the type definition
    foreach (CustomAttributeHandle attrHandle in t.GetCustomAttributes())
    {
        CustomAttribute attr = mr.GetCustomAttribute(attrHandle);

        // Display the attribute type full name
        if (attr.Constructor.Kind == HandleKind.MethodDefinition)
        {
            MethodDefinition mdef = mr.GetMethodDefinition((MethodDefinitionHandle)attr.Constructor);
            TypeDefinition tdef = mr.GetTypeDefinition(mdef.GetDeclaringType());
            Console.WriteLine($"Type:  {mr.GetString(tdef.Namespace)}.{mr.GetString(tdef.Name)}");
        }
        else if (attr.Constructor.Kind == HandleKind.MemberReference)
        {
            MemberReference mref = mr.GetMemberReference((MemberReferenceHandle)attr.Constructor);

            if (mref.Parent.Kind == HandleKind.TypeReference)
            {
                TypeReference tref = mr.GetTypeReference((TypeReferenceHandle)mref.Parent);
                Console.WriteLine($"Type:  {mr.GetString(tref.Namespace)}.{mr.GetString(tref.Name)}");
            }
            else if (mref.Parent.Kind == HandleKind.TypeDefinition)
            {
                TypeDefinition tdef = mr.GetTypeDefinition((TypeDefinitionHandle)mref.Parent);
                Console.WriteLine($"Type:  {mr.GetString(tdef.Namespace)}.{mr.GetString(tdef.Name)}");
            }
        }

        // Display the attribute value
        byte[] data = mr.GetBlobBytes(attr.Value);
        Console.Write("Value: ");

        for (int i = 0; i < data.Length; i++) Console.Write($"{data[i]:X2} ");

        Console.WriteLine();
    }
}

static void PrintTypesCustomAttributes(MetadataReader mr)
{
    foreach (TypeDefinitionHandle tdh in mr.TypeDefinitions)
    {
        TypeDefinition t = mr.GetTypeDefinition(tdh);
        Console.WriteLine($"{mr.GetString(t.Namespace)}.{mr.GetString(t.Name)}");
        PrintCustomAttributes(mr, t);
    }
}

備註

自訂屬性是一個注釋,可將其他資訊與中繼資料專案產生關聯,例如元件、類型或方法。 您可以使用 GetCustomAttribute(CustomAttributeHandle) 方法來取得自訂屬性實例。 如需 .NET 中屬性的詳細資訊,請參閱 使用屬性擴充中繼資料

屬性

Constructor

取得自訂屬性的建構函式 (MethodDefinitionHandleMemberReferenceHandle)。

Parent

取得套用屬性之中繼資料實體的控制代碼。

Value

取得屬性值。

方法

DecodeValue<TType>(ICustomAttributeTypeProvider<TType>)

解碼值 Blob 中編碼的引數。

適用於