Share via


MemberInfo.GetCustomAttributes 메서드

정의

파생 클래스에서 재정의되는 경우 이 멤버에 적용된 사용자 지정 특성을 반환합니다.

오버로드

GetCustomAttributes(Boolean)

파생 클래스에서 재정의되는 경우 이 멤버에 적용된 모든 사용자 지정 특성의 배열을 반환합니다.

GetCustomAttributes(Type, Boolean)

파생된 클래스에서 재정의하는 경우 이 멤버에 적용되고 Type으로 식별되는 사용자 지정 특성의 배열을 반환합니다.

GetCustomAttributes(Boolean)

Source:
MemberInfo.cs
Source:
MemberInfo.cs
Source:
MemberInfo.cs

파생 클래스에서 재정의되는 경우 이 멤버에 적용된 모든 사용자 지정 특성의 배열을 반환합니다.

public:
 abstract cli::array <System::Object ^> ^ GetCustomAttributes(bool inherit);
public abstract object[] GetCustomAttributes (bool inherit);
abstract member GetCustomAttributes : bool -> obj[]
Public MustOverride Function GetCustomAttributes (inherit As Boolean) As Object()

매개 변수

inherit
Boolean

이 멤버의 상속 체인을 검색하여 특성을 찾으려면 true이고 그렇지 않으면 false입니다. 이 매개 변수는 속성 및 이벤트에 대해 무시됩니다.

반환

Object[]

이 멤버에 적용된 모든 사용자 지정 특성을 포함하는 배열이며, 정의된 특성이 없는 경우 요소가 없는 배열입니다.

구현

예외

이 멤버가 리플렉션 전용 컨텍스트에 로드된 형식에 속하는 경우. 방법: 리플렉션 전용 컨텍스트에 어셈블리 로드를 참조하세요.

사용자 지정 특성 형식을 로드할 수 없는 경우

예제

다음 예제에서는 사용자 지정 특성을 정의하고 특성을 에 MyClass.MyMethod연결하고 런타임에 특성을 검색하고 결과를 표시합니다.

using namespace System;
using namespace System::Reflection;

// Define a custom attribute with one named parameter.

[AttributeUsage(AttributeTargets::All)]
public ref class MyAttribute: public Attribute
{
private:
   String^ myName;

public:
   MyAttribute( String^ name )
   {
      myName = name;
   }

   property String^ Name 
   {
      String^ get()
      {
         return myName;
      }
   }
};

// Define a class that has the custom attribute associated with one of its members.
public ref class MyClass1
{
public:

   [MyAttribute("This is an example attribute.")]
   void MyMethod( int i )
   {
      return;
   }
};

int main()
{
   try
   {
      // Get the type of MyClass1.
      Type^ myType = MyClass1::typeid;

      // Get the members associated with MyClass1.
      array<MemberInfo^>^myMembers = myType->GetMembers();

      // Display the attributes for each of the members of MyClass1.
      for ( int i = 0; i < myMembers->Length; i++ )
      {
         array<Object^>^myAttributes = myMembers[ i ]->GetCustomAttributes( true );
         if ( myAttributes->Length > 0 )
         {
            Console::WriteLine( "\nThe attributes for the member {0} are: \n", myMembers[ i ] );
            for ( int j = 0; j < myAttributes->Length; j++ )
               Console::WriteLine( "The type of the attribute is {0}.", myAttributes[ j ] );
         }
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "An exception occurred: {0}", e->Message );
   }
}
using System;
using System.Reflection;

// Define a custom attribute with one named parameter.
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    private string myName;
    public MyAttribute(string name)
    {
        myName = name;
    }
    public string Name
    {
        get
        {
            return myName;
        }
    }
}

// Define a class that has the custom attribute associated with one of its members.
public class MyClass1
{
    [MyAttribute("This is an example attribute.")]
    public void MyMethod(int i)
    {
        return;
    }
}

public class MemberInfo_GetCustomAttributes
{
    public static void Main()
    {
        try
        {
            // Get the type of MyClass1.
            Type myType = typeof(MyClass1);
            // Get the members associated with MyClass1.
            MemberInfo[] myMembers = myType.GetMembers();

            // Display the attributes for each of the members of MyClass1.
            for(int i = 0; i < myMembers.Length; i++)
            {
                Object[] myAttributes = myMembers[i].GetCustomAttributes(true);
                if(myAttributes.Length > 0)
                {
                    Console.WriteLine("\nThe attributes for the member {0} are: \n", myMembers[i]);
                    for(int j = 0; j < myAttributes.Length; j++)
                        Console.WriteLine("The type of the attribute is {0}.", myAttributes[j]);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("An exception occurred: {0}", e.Message);
        }
    }
}
Imports System.Reflection

' Define a custom attribute with one named parameter.
<AttributeUsage(AttributeTargets.All)> Public Class MyAttribute
    Inherits Attribute
    Private myName As String

    Public Sub New(ByVal name As String)
        myName = name
    End Sub

    Public ReadOnly Property Name() As String
        Get
            Return myName
        End Get
    End Property
End Class

' Define a class that has the custom attribute associated with one of its members.
Public Class MyClass1

    <MyAttribute("This is an example attribute.")> Public Sub MyMethod(ByVal i As Integer)
        Return
    End Sub
End Class


Public Class MemberInfo_GetCustomAttributes

    Public Shared Sub Main()
        Try
            ' Get the type of MyClass1.
            Dim myType As Type = GetType(MyClass1)
            ' Get the members associated with MyClass1.
            Dim myMembers As MemberInfo() = myType.GetMembers()

            ' Display the attributes for each of the members of MyClass1.
            Dim i As Integer
            For i = 0 To myMembers.Length - 1
                Dim myAttributes As [Object]() = myMembers(i).GetCustomAttributes(False)
                If myAttributes.Length > 0 Then
                    Console.WriteLine("The attributes for the member {0} are: ", myMembers(i))
                    Dim j As Integer
                    For j = 0 To myAttributes.Length - 1
                        Console.WriteLine("The type of the attribute is: {0}", myAttributes(j))
                    Next j
                End If
            Next i
        Catch e As Exception
            Console.WriteLine("An exception occurred: {0}.", e.Message)
        End Try
    End Sub
End Class

설명

이 메서드는 inherit 속성 및 이벤트에 대한 매개 변수를 무시합니다. 상속 체인에서 속성 및 이벤트에 대한 특성을 검색하려면 메서드의 적절한 오버로드를 Attribute.GetCustomAttributes 사용합니다.

참고

.NET Framework 버전 2.0에서 이 메서드는 메서드, 생성자 및 형식이 새 메타데이터 형식으로 저장된 경우 보안 특성을 반환합니다. 버전 2.0으로 컴파일된 어셈블리는 이 형식을 사용합니다. 이전 버전의 .NET Framework 컴파일된 동적 어셈블리 및 어셈블리는 이전 XML 형식을 사용합니다. 선언적 보안 특성 내보내기 를 참조하세요.

추가 정보

적용 대상

GetCustomAttributes(Type, Boolean)

Source:
MemberInfo.cs
Source:
MemberInfo.cs
Source:
MemberInfo.cs

파생된 클래스에서 재정의하는 경우 이 멤버에 적용되고 Type으로 식별되는 사용자 지정 특성의 배열을 반환합니다.

public:
 abstract cli::array <System::Object ^> ^ GetCustomAttributes(Type ^ attributeType, bool inherit);
public abstract object[] GetCustomAttributes (Type attributeType, bool inherit);
abstract member GetCustomAttributes : Type * bool -> obj[]
Public MustOverride Function GetCustomAttributes (attributeType As Type, inherit As Boolean) As Object()

매개 변수

attributeType
Type

검색할 특성의 형식입니다. 이 형식에 할당할 수 있는 특성만 반환됩니다.

inherit
Boolean

이 멤버의 상속 체인을 검색하여 특성을 찾으려면 true이고 그렇지 않으면 false입니다. 이 매개 변수는 속성 및 이벤트에 대해 무시됩니다.

반환

Object[]

이 멤버에 적용되는 사용자 지정 특성의 배열이거나, attributeType에 할당 가능한 특성이 적용되지 않은 경우 요소가 0개인 배열입니다.

구현

예외

사용자 지정 특성 형식을 로드할 수 없는 경우

attributeTypenull인 경우입니다.

이 멤버가 리플렉션 전용 컨텍스트에 로드된 형식에 속하는 경우. 방법: 리플렉션 전용 컨텍스트에 어셈블리 로드를 참조하세요.

예제

다음 예제에서는 두 개의 상속되지 않은 멤버가 있는 라는 BaseClass 클래스를 정의합니다. 즉, 라는 스레드 정적 필드와 라는 total 비 CLS 규격 메서드 MethodA입니다. 라는 DerivedClass 클래스는 에서 BaseClass 상속되고 메서드 MethodA 를 재정의합니다. 의 멤버 DerivedClass에는 특성이 적용되지 않습니다. 이 예제에서는 의 DerivedClass 멤버를 반복하여 또는 ThreadStaticAttribute 특성이 CLSCompliantAttribute 적용되었는지 여부를 확인합니다. 가 이므로 inherittrue메서드는 지정된 특성에 대한 의 DerivedClass 상속 계층 구조를 검색합니다. 예제 total 의 출력과 같이 필드는 특성으로 ThreadStaticAttribute 데코레이팅되고 MethodA 메서드는 특성으로 CLSCompliantAttribute 데코레이팅됩니다.

using System;

public class BaseClass
{
   [ThreadStatic] public int total;

   [CLSCompliant(false)] public virtual uint MethodA()
   {
      return (uint) 100;
   }
}

public class DerivedClass : BaseClass
{
   public override uint MethodA()
   {
      total++;
      return 200;
   }
}

public class Example
{
   public static void Main()
   {
      Type t = typeof(DerivedClass);
      Console.WriteLine("Members of {0}:", t.FullName);
      foreach (var m in t.GetMembers())
      {
         bool hasAttribute = false;
         Console.Write("   {0}: ", m.Name);
         if (m.GetCustomAttributes(typeof(CLSCompliantAttribute), true).Length > 0) {
            Console.Write("CLSCompliant");
            hasAttribute = true;
         }
         if (m.GetCustomAttributes(typeof(ThreadStaticAttribute), true).Length > 0) {
            Console.Write("ThreadStatic");
            hasAttribute = true;
         }
         if (! hasAttribute)
            Console.Write("No attributes");

         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//       Members of DerivedClass:
//          MethodA: CLSCompliant
//          ToString: No attributes
//          Equals: No attributes
//          GetHashCode: No attributes
//          typeof: No attributes
//          .ctor: No attributes
//          total: ThreadStatic
Public Class BaseClass
   <ThreadStatic> Public total As Integer
   
   <CLSCompliant(False)> Public Overridable Function MethodA() As UInt32
      Return CUInt(100)
   End Function
End Class

Public Class DerivedClass : Inherits BaseClass
   Public Overrides Function MethodA() As UInt32
      total += 1
      Return 200
   End Function
End Class

Module Example
   Public Sub Main()
      Dim t As Type = GetType(DerivedClass)
      Console.WriteLine("Members of {0}:", t.FullName)
      For Each m In t.GetMembers()
         Dim hasAttribute As Boolean = False
         Console.Write("   {0}: ", m.Name)
         If m.GetCustomAttributes(GetType(CLSCompliantAttribute), True).Length > 0 Then
            Console.Write("CLSCompliant")
            hasAttribute = True
         End If
         If m.GetCustomAttributes(GetType(ThreadStaticAttribute), True).Length > 0 Then
            Console.Write("ThreadStatic")
            hasAttribute = True
         End If
         If Not hasAttribute Then
            Console.Write("No attributes")
         End If
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'       Members of DerivedClass:
'          MethodA: CLSCompliant
'          ToString: No attributes
'          Equals: No attributes
'          GetHashCode: No attributes
'          GetType: No attributes
'          .ctor: No attributes
'          total: ThreadStatic

설명

이 메서드는 inherit 속성 및 이벤트에 대한 매개 변수를 무시합니다. 상속 체인에서 속성 및 이벤트에 대한 특성을 검색하려면 메서드의 적절한 오버로드를 Attribute.GetCustomAttributes 사용합니다.

참고

.NET Framework 버전 2.0에서 이 메서드는 특성이 새 메타데이터 형식으로 저장되는 경우 메서드, 생성자 및 형식에 대한 보안 특성을 반환합니다. 버전 2.0으로 컴파일된 어셈블리는 이 형식을 사용합니다. 이전 버전의 .NET Framework 컴파일된 동적 어셈블리 및 어셈블리는 이전 XML 형식을 사용합니다. 선언적 보안 특성 내보내기 를 참조하세요.

적용 대상