사용자 지정 특성 클래스를 사용하는 방법을 결정합니다.
AttributeUsage
는 사용자 지정 특성 정의에 적용하여 새 특성을 적용하는 방법을 제어할 수 있는 특성입니다. 기본 설정은 명시적으로 적용된 경우 다음과 같습니다.
<System.AttributeUsage(System.AttributeTargets.All,
AllowMultiple:=False,
Inherited:=True)>
Class NewAttribute
Inherits System.Attribute
End Class
이 예제에서는 클래스를 NewAttribute
특성 가능 코드 엔터티에 적용할 수 있지만 각 엔터티에 한 번만 적용할 수 있습니다. 기본 클래스에 적용할 때 파생 클래스에 의해 상속됩니다.
AllowMultiple
인수와 Inherited
인수는 선택 사항이므로 이 코드의 효과는 동일합니다.
<System.AttributeUsage(System.AttributeTargets.All)>
Class NewAttribute
Inherits System.Attribute
End Class
첫 번째 AttributeUsage
인수는 AttributeTargets 열거형의 요소가 하나 이상이어야 합니다. 다음과 같이 여러 대상 형식을 OR 연산자와 함께 연결할 수 있습니다.
<AttributeUsage(AttributeTargets.Property Or AttributeTargets.Field)>
Class NewPropertyOrFieldAttribute
Inherits Attribute
End Class
인수가 AllowMultiple
설정된 true
경우 다음과 같이 결과 특성을 단일 엔터티에 두 번 이상 적용할 수 있습니다.
<AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)>
Class MultiUseAttr
Inherits Attribute
End Class
<MultiUseAttr(), MultiUseAttr()>
Class Class1
End Class
이 경우 MultiUseAttr
이 AllowMultiple
로 설정되어 있기 때문에 true
을 반복적으로 적용할 수 있습니다. 여러 특성을 적용하기 위해 표시된 두 형식이 모두 유효합니다.
Inherited
이 false
로 설정되면, 특성이 지정된 클래스에서 파생된 클래스에 의해 특성이 상속되지 않습니다. 다음은 그 예입니다.
<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
단일 사용 특성이며 동일한 클래스에 두 번 이상 적용할 수 없습니다.
AttributeUsage
는 AttributeUsageAttribute의 별칭입니다.
자세한 내용은 리플렉션을 사용하여 특성 액세스(Visual Basic)를 참조하세요.
예시
다음 예제는 Inherited
특성에 대한 AllowMultiple
및 AttributeUsage
인수의 효과와 클래스에 적용된 사용자 지정 특성을 열거하는 방법을 보여 줍니다.
' 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
참고하십시오
.NET