次の方法で共有


AttributeUsage (Visual Basic)

カスタム属性クラスを使用する方法を決定します。 AttributeUsage は、カスタム属性定義に適用して、新しい属性を適用する方法を制御できる属性です。 既定の設定は、明示的に適用すると次のようになります。

<System.AttributeUsage(System.AttributeTargets.All,
                   AllowMultiple:=False,
                   Inherited:=True)>
Class NewAttribute
    Inherits System.Attribute
End Class

この例では、 NewAttribute クラスは任意の属性可能なコード エンティティに適用できますが、各エンティティに適用できるのは 1 回だけです。 基底クラスに適用すると、派生クラスによって継承されます。

AllowMultiple引数とInherited引数は省略可能であるため、このコードの効果は同じです。

<System.AttributeUsage(System.AttributeTargets.All)>
Class NewAttribute
    Inherits System.Attribute
End Class

最初の AttributeUsage 引数は、AttributeTargets 列挙型の 1 つまたは複数の要素でなければなりません。 次のように、複数のターゲット型を OR 演算子と一緒にリンクできます。

<AttributeUsage(AttributeTargets.Property Or AttributeTargets.Field)>
Class NewPropertyOrFieldAttribute
    Inherits Attribute
End Class

AllowMultiple引数が true に設定されている場合、結果の属性は、次のように 1 つのエンティティに複数回適用できます。

<AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)>
Class MultiUseAttr
    Inherits Attribute
End Class

<MultiUseAttr(), MultiUseAttr()>
Class Class1
End Class

この場合、AllowMultipletrue に設定されているため、MultiUseAttrを繰り返し適用できます。 示されているどちらの形式でも、複数の属性を適用できます。

Inheritedfalse に設定されている場合、属性は属性付きクラスから派生したクラスによって継承されません。 例えば次が挙げられます。

<AttributeUsage(AttributeTargets.Class, Inherited:=False)>
Class Attr1
    Inherits Attribute
End Class

<Attr1()>
Class BClass

End Class

Class DClass
    Inherits BClass
End Class

この場合、 Attr1 は継承によって DClass に適用されません。

注釈

AttributeUsage属性は単一使用属性です。同じクラスに複数回適用することはできません。 AttributeUsageAttributeUsageAttribute の別名です。

詳細については、「 リフレクションを使用した属性へのアクセス (Visual Basic)」を参照してください。

次の例は、AttributeUsage属性に対するInherited引数とAllowMultiple引数の効果と、クラスに適用されるカスタム属性を列挙する方法を示しています。

' Create some custom attributes:
<AttributeUsage(System.AttributeTargets.Class, Inherited:=False)>
Class A1
    Inherits System.Attribute
End Class

<AttributeUsage(System.AttributeTargets.Class)>
Class A2
    Inherits System.Attribute
End Class

<AttributeUsage(System.AttributeTargets.Class, AllowMultiple:=True)>
Class A3
    Inherits System.Attribute
End Class

' Apply custom attributes to classes:
<A1(), A2()>
Class BaseClass

End Class

<A3(), A3()>
Class DerivedClass
    Inherits BaseClass
End Class

Public Class TestAttributeUsage
    Sub Main()
        Dim b As New BaseClass
        Dim d As New DerivedClass
        ' Display custom attributes for each class.
        Console.WriteLine("Attributes on Base Class:")
        Dim attrs() As Object = b.GetType().GetCustomAttributes(True)

        For Each attr In attrs
            Console.WriteLine(attr)
        Next

        Console.WriteLine("Attributes on Derived Class:")
        attrs = d.GetType().GetCustomAttributes(True)
        For Each attr In attrs
            Console.WriteLine(attr)
        Next
    End Sub
End Class

サンプル出力

Attributes on Base Class:
A1
A2
Attributes on Derived Class:
A3
A3
A2

こちらも参照ください