다음을 통해 공유


Attribute 클래스

사용자 지정 특성에 대한 기본 클래스를 나타냅니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<SerializableAttribute> _
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
<ComVisibleAttribute(True)> _
<AttributeUsageAttribute(AttributeTargets.All, Inherited:=True, AllowMultiple:=False)> _
Public MustInherit Class Attribute
    Implements _Attribute
‘사용 방법
Dim instance As Attribute
[SerializableAttribute] 
[ClassInterfaceAttribute(ClassInterfaceType.None)] 
[ComVisibleAttribute(true)] 
[AttributeUsageAttribute(AttributeTargets.All, Inherited=true, AllowMultiple=false)] 
public abstract class Attribute : _Attribute
[SerializableAttribute] 
[ClassInterfaceAttribute(ClassInterfaceType::None)] 
[ComVisibleAttribute(true)] 
[AttributeUsageAttribute(AttributeTargets::All, Inherited=true, AllowMultiple=false)] 
public ref class Attribute abstract : _Attribute
/** @attribute SerializableAttribute() */ 
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */ 
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute AttributeUsageAttribute(AttributeTargets.All, Inherited=true, AllowMultiple=false) */ 
public abstract class Attribute implements _Attribute
SerializableAttribute 
ClassInterfaceAttribute(ClassInterfaceType.None) 
ComVisibleAttribute(true) 
AttributeUsageAttribute(AttributeTargets.All, Inherited=true, AllowMultiple=false) 
public abstract class Attribute implements _Attribute

설명

Attribute 클래스는 미리 정의된 시스템 정보나 사용자 지정 정보를 대상 요소와 연결합니다. 대상 요소는 어셈블리, 클래스, 생성자, 대리자, 열거형, 이벤트, 필드, 인터페이스, 메서드, 이식 가능한 실행 파일 모듈, 매개 변수, 속성, 반환 값, 구조체 또는 다른 특성일 수 있습니다.

특성에 의해 제공되는 정보를 메타데이터라고도 합니다. 메타데이터를 검사하여 런타임에 응용 프로그램에서 데이터를 처리하는 방법을 제어하거나 런타임 이전에 외부 도구에서 응용 프로그램이 처리되고 관리되는 방법을 제어할 수 있습니다. 예를 들어, .NET Framework에서는 특성 형식을 미리 정의한 후 이 특성을 사용하여 런타임 동작을 제어하며, 일부 프로그래밍 언어에서는 특성 형식을 사용하여 .NET Framework 공용 형식 시스템에서 직접 지원하지 않는 언어 기능을 나타냅니다.

모든 특성 형식은 Attribute 클래스에서 직접 또는 간접적으로 파생됩니다. 특성은 모든 대상 요소에 적용할 수 있습니다. 여러 특성을 같은 대상 요소에 적용할 수 있으며 특성은 대상 요소에서 파생된 요소에서 상속될 수 있습니다. AttributeTargets 클래스를 사용하여 특성이 적용되는 대상 요소를 지정할 수 있습니다.

Attribute 클래스에는 사용자 지정 특성을 편리하게 검색하고 테스트할 수 있는 메서드가 있습니다. 특성 사용에 대한 자세한 내용은 특성을 사용하여 메타데이터 확장을 참조하십시오.

예제

다음 코드 예제에서는 Attribute를 사용하는 방법을 보여 줍니다.

Imports System
Imports System.Reflection

Public Module CustomAttrVB

    ' An enumeration of animals. Start at 1 (0 = uninitialized).
    Public Enum Animal
        ' Pets
        Dog = 1
        Cat
        Bird
    End Enum

    ' Visual Basic requires the AttributeUsage be specified.
    ' A custom attribute to allow a target to have a pet.
    <AttributeUsage(AttributeTargets.Method)> _
    Public Class AnimalTypeAttribute
        Inherits Attribute

        ' The constructor is called when the attribute is set.
        Public Sub New(ByVal animal As Animal)
            Me.thePet = animal
        End Sub

        ' Keep a variable internally ...
        Protected thePet As Animal

        ' .. and show a copy to the outside world.
        Public Property Pet() As Animal
            Get
                Return thePet
            End Get
            Set(ByVal Value As Animal)
                thePet = Value
            End Set
        End Property

    End Class

    ' A test class where each method has its own pet.
    Class AnimalTypeTestClass

        <AnimalType(Animal.Dog)> _
        Public Sub DogMethod()
        End Sub

        <AnimalType(Animal.Cat)> _
        Public Sub CatMethod()
        End Sub

        <AnimalType(Animal.Bird)> _
        Public Sub BirdMethod()
        End Sub
    End Class

    ' The runtime test.
    Sub Main()
        Dim testClass As New AnimalTypeTestClass()
        Dim tcType As Type = testClass.GetType()
        Dim mInfo As MethodInfo
        ' Iterate through all the methods of the class.
        For Each mInfo In tcType.GetMethods()
            Dim attr As Attribute
            ' Iterate through all the attributes of the method.
            For Each attr In Attribute.GetCustomAttributes(mInfo)
                If TypeOf attr Is AnimalTypeAttribute Then
                    Dim attrCustom As AnimalTypeAttribute = _
                        CType(attr, AnimalTypeAttribute)
                    Console.WriteLine("Method {0} has a pet {1} attribute.", _
                         mInfo.Name(), attrCustom.Pet.ToString())
                End If
            Next
        Next
    End Sub
End Module

' Output:
' Method DogMethod has a pet Dog attribute.
' Method CatMethod has a pet Cat attribute.
' Method BirdMethod has a pet Bird attribute.
using System;
using System.Reflection;

namespace CustomAttrCS {
    // An enumeration of animals. Start at 1 (0 = uninitialized).
    public enum Animal {
        // Pets.
        Dog = 1,
        Cat,
        Bird,
    }

    // A custom attribute to allow a target to have a pet.
    public class AnimalTypeAttribute : Attribute {
        // The constructor is called when the attribute is set.
        public AnimalTypeAttribute(Animal pet) {
            thePet = pet;
        }

        // Keep a variable internally ...
        protected Animal thePet;

        // .. and show a copy to the outside world.
        public Animal Pet {
            get { return thePet; }
            set { thePet = Pet; }
        }
    }

    // A test class where each method has its own pet.
    class AnimalTypeTestClass {
        [AnimalType(Animal.Dog)]
        public void DogMethod() {}

        [AnimalType(Animal.Cat)]
        public void CatMethod() {}

        [AnimalType(Animal.Bird)]
        public void BirdMethod() {}
    }

    class DemoClass {
        static void Main(string[] args) {
            AnimalTypeTestClass testClass = new AnimalTypeTestClass();
            Type type = testClass.GetType();
            // Iterate through all the methods of the class.
            foreach(MethodInfo mInfo in type.GetMethods()) {
                // Iterate through all the Attributes for each method.
                foreach (Attribute attr in 
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the AnimalType attribute.
                    if (attr.GetType() == typeof(AnimalTypeAttribute))
                        Console.WriteLine(
                            "Method {0} has a pet {1} attribute.", 
                            mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
                }

            }
        }
    }
}

/*
 * Output:
 * Method DogMethod has a pet Dog attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method BirdMethod has a pet Bird attribute.
 */
using namespace System;
using namespace System::Reflection;

// An enumeration of animals. Start at 1 (0 = uninitialized).
public enum class Animal
{
   // Pets.
   Dog = 1,
   Cat, Bird
};

// A custom attribute to allow a target to have a pet.
public ref class AnimalTypeAttribute: public Attribute
{
public:

   // The constructor is called when the attribute is set.
   AnimalTypeAttribute( Animal pet )
   {
      thePet = pet;
   }


protected:

   // Keep a variable internally ...
   Animal thePet;

public:

   property Animal Pet 
   {
      // .. and show a copy to the outside world.
      Animal get()
      {
         return thePet;
      }

      void set( Animal value )
      {
         thePet = value;
      }
   }
};

// A test class where each method has its own pet.
ref class AnimalTypeTestClass
{
public:

   [AnimalType(Animal::Dog)]
   void DogMethod(){}


   [AnimalType(Animal::Cat)]
   void CatMethod(){}

   [AnimalType(Animal::Bird)]
   void BirdMethod(){}

};

int main()
{
   AnimalTypeTestClass^ testClass = gcnew AnimalTypeTestClass;
   Type^ type = testClass->GetType();

   // Iterate through all the methods of the class.
   System::Collections::IEnumerator^ myEnum = type->GetMethods()->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      MethodInfo^ mInfo = safe_cast<MethodInfo^>(myEnum->Current);

      // Iterate through all the Attributes for each method.
      System::Collections::IEnumerator^ myEnum1 = Attribute::GetCustomAttributes( mInfo )->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         Attribute^ attr = safe_cast<Attribute^>(myEnum1->Current);

         // Check for the AnimalType attribute.
         if ( attr->GetType() == AnimalTypeAttribute::typeid )
                  Console::WriteLine( "Method {0} has a pet {1} attribute.", mInfo->Name, (dynamic_cast<AnimalTypeAttribute^>(attr))->Pet );
      }
   }
}

/*
 * Output:
 * Method DogMethod has a pet Dog attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method BirdMethod has a pet Bird attribute.
 */
package CustomAttrJSL; 

import System.*;
import System.Reflection.*;
  
public class Animal
{
    protected int pet;
    public static final int dog = 1;
    public static final int cat = 2;
    public static final int bird = 3;

    public Animal()
    {
        pet = 0;
    } //Animal
    public Animal(int p)
    {
        pet = p;
    } //Animal
    public String getPet()
    {
        switch (pet) {
            case 1 :
                return "Dog";
            case 2 :
                return "Cat";
            case 3 :
                return "Bird";
            default :
                return null;
        }
    } //getPet
} //Animal
      
// A custom attribute to allow a target to have a pet.
/** @attribute System.AttributeUsageAttribute(AttributeTargets.Method)
 */
public class AnimalTypeAttribute extends Attribute
{
    public AnimalTypeAttribute() { }
    // The constructor is called when the attribute is set.
    public AnimalTypeAttribute(int pet)
    {
        thePet = new Animal(pet);
    } //AnimalTypeAttribute

    // Keep a variable internally...
    protected Animal thePet;

    //.. and show a copy to the outside world.
    /** @property 
     */
    public Animal get_Pet()
    {
        return thePet;
    } //get_Pet

    /** @property 
     */
    public void set_Pet(Animal value)
    {
        thePet = value;
    } //set_Pet
} //AnimalTypeAttribute
      
 // A test class where each method has its own pet.
class AnimalTypeTestClass
{
    /** @attribute AnimalType(Animal.dog)
     */
    public void DogMethod()
    {
    } //DogMethod

    /** @attribute AnimalType(Animal.cat)
     */
    public void CatMethod()
    {
    } //CatMethod

    /** @attribute AnimalType(Animal.bird)
     */
    public void BirdMethod()
    {
    } //BirdMethod
} //AnimalTypeTestClass
   
class DemoClass
{
    public static void main(String[] args)
    {
        AnimalTypeTestClass testClass = new AnimalTypeTestClass();
        Type type = testClass.GetType();
        // Iterate through all the methods of the class.
        for (int iCtr1 = 0; iCtr1 < type.GetMethods().length; iCtr1++) {
            MethodInfo mInfo = type.GetMethods()[iCtr1];
            // Iterate through all the Attributes for each method.
            for (int iCtr2 = 0; 
                iCtr2 < Attribute.GetCustomAttributes(mInfo).length; 
                iCtr2++) {
               
                Attribute attr = Attribute.GetCustomAttributes(mInfo)[iCtr2];
                // Check for the AnimalType attribute.
                if (attr.GetType().
                    Equals(AnimalTypeAttribute.class.ToType())) {                
                    Console.WriteLine("Method {0} has a pet {1} attribute.", 
                        mInfo.get_Name(), 
                        ((AnimalTypeAttribute)attr).get_Pet().getPet());
                }
            }
        }
    } //main
} //DemoClass 

/*
 Output:
 Method DogMethod has a pet Dog attribute.
 Method CatMethod has a pet Cat attribute.
 Method BirdMethod has a pet Bird attribute.
*/
import System;
import System.Reflection;
import CustomAttrJS;

package CustomAttrJS {
    // An enumeration of animals. Start at 1 (0 = uninitialized).
    public enum Animal {
        // Pets.
        Dog = 1,
        Cat,
        Bird,
    }

    // A custom attribute to allow a target to have a pet.
    public AttributeUsage(AttributeTargets.Method) class AnimalTypeAttribute extends Attribute {
        // The constructor is called when the attribute is set.
        public function AnimalTypeAttribute(pet : Animal) {
            thePet = pet;
        }

        // Keep a variable internally ...
        protected var thePet : Animal;

        // .. and show a copy to the outside world.
        public function get Pet() : Animal {
                    return thePet; 
                }
        
                public function set Pet(pet : Animal) {
                    thePet = pet; 
                }
    }

    // A test class where each method has its own pet.
    class AnimalTypeTestClass {
        public AnimalTypeAttribute(Animal.Dog) 
                function DogMethod() {}

        public AnimalTypeAttribute(Animal.Cat)
        function CatMethod() {}

        public AnimalTypeAttribute(Animal.Bird)
        function BirdMethod() {}
    }
}



var testClass : AnimalTypeTestClass = new AnimalTypeTestClass();
var type : Type = testClass.GetType();
// Iterate through all the methods of the class.
            var mInfo : MethodInfo[] = type.GetMethods();
for (var i : int = 0; i < mInfo.length; i++) {
    // Iterate through all the Attributes for each method.
                    var attr : Attribute[] = Attribute.GetCustomAttributes(mInfo[i]);
    for (var j : int = 0; j < attr.length; j++) 
    {
        // Check for the AnimalType attribute.
        if (attr[j].GetType() == AnimalTypeAttribute)
            Console.WriteLine(
                "Method {0} has a pet {1} attribute.", 
                mInfo[i].Name, AnimalTypeAttribute(attr[j]).Pet);
    }

}


/*
 * Output:
 * Method BirdMethod has a pet Bird attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method DogMethod has a pet Dog attribute.
 */

상속 계층 구조

System.Object
  System.Attribute
     파생 클래스

스레드로부터의 안전성

이 형식은 다중 스레드 작업을 수행하는 데 안전합니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Attribute 멤버
System 네임스페이스