Aracılığıyla paylaş


Attribute.GetCustomAttribute Yöntem

Tanım

Bir derlemeye, modüle, tür üyesine veya yöntem parametresine uygulanan belirtilen türde özel bir özniteliği alır.

Aşırı Yüklemeler

GetCustomAttribute(ParameterInfo, Type, Boolean)

Yöntem parametresine uygulanan özel bir özniteliği alır. Parametreler yöntem parametresini, aranacak özel özniteliğin türünü ve yöntem parametresinin alt öğelerinde arama yapılıp yapılmayacağını belirtir.

GetCustomAttribute(MemberInfo, Type, Boolean)

Türün bir üyesine uygulanan özel bir özniteliği alır. Parametreler üyeyi, aranacak özel özniteliğin türünü ve üyenin atalarının aranıp aranmayacağını belirtir.

GetCustomAttribute(Assembly, Type, Boolean)

Derlemeye uygulanan özel bir özniteliği alır. Parametreler derlemeyi, aranacak özel özniteliğin türünü ve yoksayılan arama seçeneğini belirtir.

GetCustomAttribute(Module, Type, Boolean)

Modüle uygulanan özel bir özniteliği alır. Parametreler modülü, aranacak özel özniteliğin türünü ve yoksayılan arama seçeneğini belirtir.

GetCustomAttribute(Module, Type)

Modüle uygulanan özel bir özniteliği alır. Parametreler modülü ve aranacak özel özniteliğin türünü belirtir.

GetCustomAttribute(MemberInfo, Type)

Türün bir üyesine uygulanan özel bir özniteliği alır. Parametreler, üyeyi ve aranacak özel özniteliğin türünü belirtir.

GetCustomAttribute(Assembly, Type)

Belirtilen derlemeye uygulanan özel bir özniteliği alır. Parametreler, aranacak özel özniteliğin derlemesini ve türünü belirtir.

GetCustomAttribute(ParameterInfo, Type)

Yöntem parametresine uygulanan özel bir özniteliği alır. Parametreler yöntem parametresini ve aranacak özel özniteliğin türünü belirtir.

GetCustomAttribute(ParameterInfo, Type, Boolean)

Yöntem parametresine uygulanan özel bir özniteliği alır. Parametreler yöntem parametresini, aranacak özel özniteliğin türünü ve yöntem parametresinin alt öğelerinde arama yapılıp yapılmayacağını belirtir.

public:
 static Attribute ^ GetCustomAttribute(System::Reflection::ParameterInfo ^ element, Type ^ attributeType, bool inherit);
public static Attribute? GetCustomAttribute (System.Reflection.ParameterInfo element, Type attributeType, bool inherit);
public static Attribute GetCustomAttribute (System.Reflection.ParameterInfo element, Type attributeType, bool inherit);
static member GetCustomAttribute : System.Reflection.ParameterInfo * Type * bool -> Attribute
Public Shared Function GetCustomAttribute (element As ParameterInfo, attributeType As Type, inherit As Boolean) As Attribute

Parametreler

element
ParameterInfo

Sınıfın bir üyesinin ParameterInfo parametresini açıklayan sınıfından türetilmiş bir nesne.

attributeType
Type

Aranacak özel özniteliğin türü veya temel türü.

inherit
Boolean

ise true, öğesinin atalarını element özel öznitelikler için de aramayı belirtir.

Döndürülenler

Attribute

türüne uygulanan veya null böyle bir öznitelik yoksa türündeki attributeType tek özel özniteliğe elementbaşvuru.

Özel durumlar

element veya attributeType şeklindedir null.

attributeType , 'den Attributetüretilmemiştir.

İstenen özniteliklerden birden fazlası bulundu.

Özel öznitelik türü yüklenemiyor.

Örnekler

Aşağıdaki kod örneği özel parametre Attribute sınıfını tanımlar ve özel özniteliği türetilmiş bir sınıftaki bir yönteme ve türetilmiş sınıfın tabanına uygular. Örnekte öznitelikleri döndürmek için yönteminin kullanımı GetCustomAttribute gösterilmektedir.

// Example for the Attribute::GetCustomAttribute( ParameterInfo*, Type*, bool ) 
// method.
using namespace System;
using namespace System::Collections;
using namespace System::Reflection;

namespace NDP_UE_CPP
{
   // Define a custom parameter attribute that takes a single message argument.

   [AttributeUsage(AttributeTargets::Parameter)]
   public ref class ArgumentUsageAttribute: public Attribute
   {
   protected:

      // usageMsg is storage for the attribute message.
      String^ usageMsg;

   public:

      // This is the attribute constructor.
      ArgumentUsageAttribute( String^ UsageMsg )
      {
         this->usageMsg = UsageMsg;
      }

      property String^ Message 
      {
         // This is the Message property for the attribute.
         String^ get()
         {
            return usageMsg;
         }

         void set( String^ value )
         {
            this->usageMsg = value;
         }
      }
   };

   public ref class BaseClass
   {
   public:

      // Assign an ArgumentUsage attribute to the strArray parameter.
      // Assign a ParamArray attribute to strList.
      virtual void TestMethod( [ArgumentUsage("Must pass an array here.")]array<String^>^strArray,
                               ...array<String^>^strList ){}
   };

   public ref class DerivedClass: public BaseClass
   {
   public:

      // Assign an ArgumentUsage attributes to the strList parameter.
      virtual void TestMethod( array<String^>^strArray, [ArgumentUsage(
      "Can pass a parameter list or array here.")]array<String^>^strList ) override {}

   };

   void DisplayParameterAttributes( MethodInfo^ mInfo, array<ParameterInfo^>^pInfoArray, bool includeInherited )
   {
      Console::WriteLine( "\nParameter attribute information for method \"{0}"
      "\"\nincludes inheritance from base class: {1}.", mInfo->Name, includeInherited ? (String^)"Yes" : "No" );
      
      // This implements foreach( ParameterInfo* paramInfo in pInfoArray ).
      IEnumerator^ myEnum = pInfoArray->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         ParameterInfo^ paramInfo = safe_cast<ParameterInfo^>(myEnum->Current);

         // See if the ParamArray attribute is defined.
         bool isDef = Attribute::IsDefined( paramInfo, ParamArrayAttribute::typeid );
         if ( isDef )
                  Console::WriteLine( "\n    The ParamArray attribute is defined "
         "for \n    parameter {0} of method {1}.", paramInfo->Name, mInfo->Name );

         // See if ParamUsageAttribute is defined.  
         // If so, display a message.
         ArgumentUsageAttribute^ usageAttr = static_cast<ArgumentUsageAttribute^>(Attribute::GetCustomAttribute( paramInfo, ArgumentUsageAttribute::typeid, includeInherited ));
         if ( usageAttr != nullptr )
         {
            Console::WriteLine( "\n    The ArgumentUsage attribute is defined "
            "for \n    parameter {0} of method {1}.", paramInfo->Name, mInfo->Name );
            Console::WriteLine( "\n        The usage "
            "message for {0} is:\n        \"{1}\".", paramInfo->Name, usageAttr->Message );
         }
      }
   }

}

int main()
{
   Console::WriteLine( "This example of Attribute::GetCustomAttribute( ParameterInfo*, "
   "Type*, bool )\ngenerates the following output." );

   // Get the class type, and then get the MethodInfo object 
   // for TestMethod to access its metadata.
   Type^ clsType = NDP_UE_CPP::DerivedClass::typeid;
   MethodInfo^ mInfo = clsType->GetMethod(  "TestMethod" );

   // Iterate through the ParameterInfo array for the method parameters.
   array<ParameterInfo^>^pInfoArray = mInfo->GetParameters();
   if ( pInfoArray != nullptr )
   {
      NDP_UE_CPP::DisplayParameterAttributes( mInfo, pInfoArray, false );
      NDP_UE_CPP::DisplayParameterAttributes( mInfo, pInfoArray, true );
   }
   else
      Console::WriteLine( "The parameters information could "
   "not be retrieved for method {0}.", mInfo->Name );
}

/*
This example of Attribute::GetCustomAttribute( ParameterInfo*, Type*, bool )
generates the following output.

Parameter attribute information for method "TestMethod"
includes inheritance from base class: No.

    The ParamArray attribute is defined for
    parameter strList of method TestMethod.

    The ArgumentUsage attribute is defined for
    parameter strList of method TestMethod.

        The usage message for strList is:
        "Can pass a parameter list or array here.".

Parameter attribute information for method "TestMethod"
includes inheritance from base class: Yes.

    The ArgumentUsage attribute is defined for
    parameter strArray of method TestMethod.

        The usage message for strArray is:
        "Must pass an array here.".

    The ParamArray attribute is defined for
    parameter strList of method TestMethod.

    The ArgumentUsage attribute is defined for
    parameter strList of method TestMethod.

        The usage message for strList is:
        "Can pass a parameter list or array here.".
*/
// Example for the Attribute.GetCustomAttribute( ParameterInfo, Type, Boolean )
// method.
using System;
using System.Reflection;

namespace NDP_UE_CS
{
    // Define a custom parameter attribute that takes a single message argument.
    [AttributeUsage( AttributeTargets.Parameter )]
    public class ArgumentUsageAttribute : Attribute
    {
        // This is the attribute constructor.
        public ArgumentUsageAttribute( string UsageMsg )
        {
            this.usageMsg = UsageMsg;
        }

        // usageMsg is storage for the attribute message.
        protected string usageMsg;

        // This is the Message property for the attribute.
        public string Message
        {
            get { return usageMsg; }
            set { usageMsg = value; }
        }
    }

    public class BaseClass
    {
        // Assign an ArgumentUsage attribute to the strArray parameter.
        // Assign a ParamArray attribute to strList using the params keyword.
        public virtual void TestMethod(
            [ArgumentUsage("Must pass an array here.")]
            String[] strArray,
            params String[] strList)
        { }
    }

    public class DerivedClass : BaseClass
    {
        // Assign an ArgumentUsage attribute to the strList parameter.
        // Assign a ParamArray attribute to strList using the params keyword.
        public override void TestMethod(
            String[] strArray,
            [ArgumentUsage("Can pass a parameter list or array here.")]
            params String[] strList)
        { }
    }

    class CustomParamDemo
    {
        static void Main( )
        {
            Console.WriteLine(
                "This example of Attribute.GetCustomAttribute( Parameter" +
                "Info, Type, Boolean )\ngenerates the following output." );

            // Get the class type, and then get the MethodInfo object
            // for TestMethod to access its metadata.
            Type clsType = typeof(DerivedClass);
            MethodInfo mInfo = clsType.GetMethod("TestMethod");

            // Iterate through the ParameterInfo array for the method parameters.
            ParameterInfo[] pInfoArray = mInfo.GetParameters();
            if (pInfoArray != null)
            {
                DisplayParameterAttributes( mInfo, pInfoArray, false );
                DisplayParameterAttributes( mInfo, pInfoArray, true );
            }
            else
                Console.WriteLine("The parameters information could " +
                    "not be retrieved for method {0}.", mInfo.Name);
        }

        static void DisplayParameterAttributes( MethodInfo mInfo,
            ParameterInfo[] pInfoArray, bool includeInherited )
        {
            Console.WriteLine(
                "\nParameter attribute information for method \"" +
                "{0}\"\nincludes inheritance from base class: {1}.",
                mInfo.Name, includeInherited ? "Yes" : "No" );

            // Display the attribute information for the parameters.
            foreach( ParameterInfo paramInfo in pInfoArray )
            {
                // See if the ParamArray attribute is defined.
                bool isDef = Attribute.IsDefined( paramInfo,
                    typeof(ParamArrayAttribute));

                if( isDef )
                    Console.WriteLine(
                        "\n    The ParamArray attribute is defined " +
                        "for \n    parameter {0} of method {1}.",
                        paramInfo.Name, mInfo.Name);

                // See if ParamUsageAttribute is defined.
                // If so, display a message.
                ArgumentUsageAttribute usageAttr = (ArgumentUsageAttribute)
                    Attribute.GetCustomAttribute( paramInfo,
                        typeof(ArgumentUsageAttribute),
                        includeInherited );

                if( usageAttr != null )
                {
                    Console.WriteLine(
                        "\n    The ArgumentUsage attribute is def" +
                        "ined for \n    parameter {0} of method {1}.",
                        paramInfo.Name, mInfo.Name );

                    Console.WriteLine( "\n        The usage " +
                        "message for {0} is:\n        \"{1}\".",
                        paramInfo.Name, usageAttr.Message);
                }
            }
        }
    }
}

/*
This example of Attribute.GetCustomAttribute( ParameterInfo, Type, Boolean )
generates the following output.

Parameter attribute information for method "TestMethod"
includes inheritance from base class: No.

    The ParamArray attribute is defined for
    parameter strList of method TestMethod.

    The ArgumentUsage attribute is defined for
    parameter strList of method TestMethod.

        The usage message for strList is:
        "Can pass a parameter list or array here.".

Parameter attribute information for method "TestMethod"
includes inheritance from base class: Yes.

    The ArgumentUsage attribute is defined for
    parameter strArray of method TestMethod.

        The usage message for strArray is:
        "Must pass an array here.".

    The ParamArray attribute is defined for
    parameter strList of method TestMethod.

    The ArgumentUsage attribute is defined for
    parameter strList of method TestMethod.

        The usage message for strList is:
        "Can pass a parameter list or array here.".
*/
open System
open System.Reflection

// Define a custom parameter attribute that takes a single message argument.
[<AttributeUsage(AttributeTargets.Parameter); AllowNullLiteral>]
type ArgumentUsageAttribute(usageMsg) =
    inherit Attribute()

    // This is the Message property for the attribute.
    member val Message: string = usageMsg

type BaseClass() =
    // Assign an ArgumentUsage attribute to the strArray parameter.
    // Assign a ParamArray attribute to strList.
    abstract member TestMethod: string [] * string[] -> unit
    default _.TestMethod(
        [<ArgumentUsage "Must pass an array here.">]
        strArray,
        [<ParamArray>]
        strList) = ()

type DerivedClass() =
    inherit BaseClass()
    // Assign an ArgumentUsage attribute to the strList parameter.
    // Assign a ParamArray attribute to strList.
    override _.TestMethod(
        strArray,
        [<ArgumentUsage "Can pass a parameter list or array here."; ParamArray>]
        strList) = ()

let displayParameterAttributes (mInfo: MethodInfo) (pInfoArray: ParameterInfo []) includeInherited =
    printfn $"""
Parameter attribute information for method "{mInfo.Name}"
includes inheritance from base class: {if includeInherited then "Yes" else "No"}."""

    // Display the attribute information for the parameters.
    for paramInfo in pInfoArray do
        // See if the ParamArray attribute is defined.
        let isDef = Attribute.IsDefined(paramInfo, typeof<ParamArrayAttribute>)

        if isDef then
            printfn $"\n    The ParamArray attribute is defined for \n    parameter {paramInfo.Name} of method {mInfo.Name}."

        // See if ParamUsageAttribute is defined.
        // If so, display a message.
        let usageAttr =
            Attribute.GetCustomAttribute(paramInfo, typeof<ArgumentUsageAttribute>, includeInherited)
            :?> ArgumentUsageAttribute

        if usageAttr <> null then
            printfn $"\n    The ArgumentUsage attribute is defined for \n    parameter {paramInfo.Name} of method {mInfo.Name}." 
            printfn $"\n        The usage message for {paramInfo.Name} is:\n        \"{usageAttr.Message}\"."

printfn "This example of Attribute.GetCustomAttribute(ParameterInfo, Type, Boolean)\ngenerates the following output."

// Get the class type, and then get the MethodInfo object
// for TestMethod to access its metadata.
let clsType = typeof<DerivedClass>
let mInfo = clsType.GetMethod "TestMethod"

// Iterate through the ParameterInfo array for the method parameters.
let pInfoArray = mInfo.GetParameters()
if pInfoArray <> null then
    displayParameterAttributes mInfo pInfoArray false
    displayParameterAttributes mInfo pInfoArray true
else
    printfn $"The parameters information could not be retrieved for method {mInfo.Name}."


// This example of Attribute.GetCustomAttribute( ParameterInfo, Type, Boolean )
// generates the following output.
// 
// Parameter attribute information for method "TestMethod"
// includes inheritance from base class: No.
// 
//     The ParamArray attribute is defined for
//     parameter strList of method TestMethod.
// 
//     The ArgumentUsage attribute is defined for
//     parameter strList of method TestMethod.
// 
//         The usage message for strList is:
//         "Can pass a parameter list or array here.".
// 
// Parameter attribute information for method "TestMethod"
// includes inheritance from base class: Yes.
// 
//     The ArgumentUsage attribute is defined for
//     parameter strArray of method TestMethod.
// 
//         The usage message for strArray is:
//         "Must pass an array here.".
// 
//     The ParamArray attribute is defined for
//     parameter strList of method TestMethod.
// 
//     The ArgumentUsage attribute is defined for
//     parameter strList of method TestMethod.
// 
//         The usage message for strList is:
//         "Can pass a parameter list or array here.".
' Example for the Attribute.GetCustomAttribute( ParameterInfo, Type, Boolean ) 
' method.
Imports System.Reflection

Namespace NDP_UE_VB

    ' Define a custom parameter attribute that takes a single message argument.
    <AttributeUsage(AttributeTargets.Parameter)>  _
    Public Class ArgumentUsageAttribute
        Inherits Attribute
           
        ' This is the attribute constructor.
        Public Sub New(UsageMsg As String)
            Me.usageMsg = UsageMsg
        End Sub

        ' usageMsg is storage for the attribute message.
        Protected usageMsg As String
           
        ' This is the Message property for the attribute.
        Public Property Message() As String
            Get
                Return usageMsg
            End Get
            Set
                usageMsg = value
            End Set
        End Property
    End Class

    Public Class BaseClass
       
        ' Assign an ArgumentUsage attribute to the strArray parameter.
        ' Assign a ParamArray attribute to the strList parameter.
        Public Overridable Sub TestMethod( _
            <ArgumentUsage("Must pass an array here.")> _
            strArray() As String, _
            ParamArray strList() As String)
        End Sub
    End Class

    Public Class DerivedClass
        Inherits BaseClass
           
        ' Assign an ArgumentUsage attribute to the strList parameter.
        ' Assign a ParamArray attribute to the strList parameter.
        Public Overrides Sub TestMethod( _
            strArray() As String, _
            <ArgumentUsage("Can pass a parameter list or array here.")> _
            ParamArray strList() As String)
        End Sub
    End Class

    Class DemoClass
           
        Shared Sub DisplayParameterAttributes(mInfo As MethodInfo, _
            pInfoArray() As ParameterInfo, includeInherited As Boolean)

            Console.WriteLine( vbCrLf & _
                "Parameter attribute information for method ""{0}""" & _
                vbCrLf & "includes inheritance from the base class: {1}.", _
                mInfo.Name, IIf(includeInherited, "Yes", "No"))
              
            ' Display attribute information for the parameters.
            Dim paramInfo As ParameterInfo
            For Each paramInfo In  pInfoArray

                ' See if the ParamArray attribute is defined.
                Dim isDef As Boolean = _
                    Attribute.IsDefined(paramInfo, GetType(ParamArrayAttribute))

                If isDef Then
                    Console.WriteLine( vbCrLf & "    The " & _
                        "ParamArray attribute is defined for " & _
                        vbCrLf & "    parameter {0} of method {1}.", _
                        paramInfo.Name, mInfo.Name)
                End If
                 
                ' See if ParamUsageAttribute is defined.  
                ' If so, display a message.
                Dim usageAttr As ArgumentUsageAttribute = _
                    Attribute.GetCustomAttribute(paramInfo, _
                        GetType(ArgumentUsageAttribute), _
                        includeInherited)

                If Not (usageAttr Is Nothing) Then
                    Console.WriteLine( vbCrLf & "    The " & _
                        "ArgumentUsage attribute is defined for " & _
                        vbCrLf & "    parameter {0} of method {1}.", _
                        paramInfo.Name, mInfo.Name)
                    Console.WriteLine( vbCrLf & _
                        "        The usage message for {0} is: " & _
                        vbCrLf & "        ""{1}"".", _
                        paramInfo.Name, usageAttr.Message)
                End If
            Next paramInfo
        End Sub
       
        Public Shared Sub Main()
            Console.WriteLine( _
                "This example of Attribute.GetCustomAttribute" & _
                "( ParameterInfo, Type, Boolean )" & vbCrLf & _
                "generates the following output." )
              
            ' Get the class type, and then get the MethodInfo object 
            ' for TestMethod to access its metadata.
            Dim clsType As Type = GetType(DerivedClass)
            Dim mInfo As MethodInfo = clsType.GetMethod("TestMethod")
              
            ' Iterate through the ParameterInfo array for the method parameters.
            Dim pInfoArray As ParameterInfo() = mInfo.GetParameters()
            If Not (pInfoArray Is Nothing) Then

                DisplayParameterAttributes(mInfo, pInfoArray, False)
                DisplayParameterAttributes(mInfo, pInfoArray, True)
            Else
                Console.WriteLine( _
                    "The parameters information could " & _
                    "not be retrieved for method {0}.", mInfo.Name)
            End If
        End Sub

    End Class
End Namespace ' NDP_UE_VB

' This example of Attribute.GetCustomAttribute( ParameterInfo, Type, Boolean )
' generates the following output.
' 
' Parameter attribute information for method "TestMethod"
' includes inheritance from the base class: No.
' 
'     The ParamArray attribute is defined for
'     parameter strList of method TestMethod.
' 
'     The ArgumentUsage attribute is defined for
'     parameter strList of method TestMethod.
' 
'         The usage message for strList is:
'         "Can pass a parameter list or array here.".
' 
' Parameter attribute information for method "TestMethod"
' includes inheritance from the base class: Yes.
' 
'     The ArgumentUsage attribute is defined for
'     parameter strArray of method TestMethod.
' 
'         The usage message for strArray is:
'         "Must pass an array here.".
' 
'     The ParamArray attribute is defined for
'     parameter strList of method TestMethod.
' 
'     The ArgumentUsage attribute is defined for
'     parameter strList of method TestMethod.
' 
'         The usage message for strList is:
'         "Can pass a parameter list or array here.".

Açıklamalar

Türetilmiş bir türün yöntemindeki bir parametreyi temsil ederse element , dönüş değeri geçersiz kılınan temel yöntemlerde aynı parametreye uygulanan devralınabilir özel öznitelikleri içerir.

Şunlara uygulanır

GetCustomAttribute(MemberInfo, Type, Boolean)

Türün bir üyesine uygulanan özel bir özniteliği alır. Parametreler üyeyi, aranacak özel özniteliğin türünü ve üyenin atalarının aranıp aranmayacağını belirtir.

public:
 static Attribute ^ GetCustomAttribute(System::Reflection::MemberInfo ^ element, Type ^ attributeType, bool inherit);
public static Attribute? GetCustomAttribute (System.Reflection.MemberInfo element, Type attributeType, bool inherit);
public static Attribute GetCustomAttribute (System.Reflection.MemberInfo element, Type attributeType, bool inherit);
static member GetCustomAttribute : System.Reflection.MemberInfo * Type * bool -> Attribute
Public Shared Function GetCustomAttribute (element As MemberInfo, attributeType As Type, inherit As Boolean) As Attribute

Parametreler

element
MemberInfo

Bir sınıfın oluşturucu, MemberInfo olay, alan, yöntem veya özellik üyesini tanımlayan sınıfından türetilen nesne.

attributeType
Type

Aranacak özel özniteliğin türü veya temel türü.

inherit
Boolean

ise true, öğesinin atalarında element da özel öznitelikler aranacak şekilde belirtir.

Döndürülenler

Attribute

türüne uygulanan elementtek bir özel özniteliğine attributeType başvuru veya null böyle bir öznitelik yoksa.

Özel durumlar

element veya attributeType şeklindedir null.

attributeType , 'den Attributetüretilmemiştir.

element oluşturucu, yöntem, özellik, olay, tür veya alan değildir.

İstenen özniteliklerden birden fazlası bulundu.

Özel öznitelik türü yüklenemiyor.

Örnekler

Aşağıdaki kod örneği, parametre olarak bir alan MemberInfo yönteminin GetCustomAttribute kullanımını gösterir.

using namespace System;
using namespace System::Reflection;

namespace IsDef4CS
{
   public ref class TestClass
   {
   public:

      // Assign the Obsolete attribute to a method.

      [Obsolete("This method is obsolete. Use Method2 instead.")]
      void Method1(){}

      void Method2(){}

   };

   ref class DemoClass
   {
   public:
      static void Main()
      {
         
         // Get the class type to access its metadata.
         Type^ clsType = TestClass::typeid;
         
         // Get the MethodInfo object for Method1.
         MethodInfo^ mInfo = clsType->GetMethod( "Method1" );
         
         // See if the Obsolete attribute is defined for this method.
         bool isDef = Attribute::IsDefined( mInfo, ObsoleteAttribute::typeid );
         
         // Display the result.
         Console::WriteLine( "The Obsolete Attribute {0} defined for {1} of class {2}.", isDef ? (String^)"is" : "is not", mInfo->Name, clsType->Name );
         
         // If it's defined, display the attribute's message.
         if ( isDef )
         {
            ObsoleteAttribute^ obsAttr = dynamic_cast<ObsoleteAttribute^>(Attribute::GetCustomAttribute( mInfo, ObsoleteAttribute::typeid ));
            if ( obsAttr != nullptr )
                        Console::WriteLine( "The message is: \"{0}\".", obsAttr->Message );
            else
                        Console::WriteLine( "The message could not be retrieved." );
         }
      }

   };

}


/*
 * Output:
 * The Obsolete Attribute is defined for Method1 of class TestClass.
 * The message is: "This method is obsolete. Use Method2 instead.".
 */
using System;
using System.Reflection;

namespace IsDef4CS
{
    public class TestClass
    {
        // Assign the Obsolete attribute to a method.
        [Obsolete("This method is obsolete. Use Method2 instead.")]
        public void Method1()
        {}
        public void Method2()
        {}
    }

    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(TestClass);
            // Get the MethodInfo object for Method1.
            MethodInfo mInfo = clsType.GetMethod("Method1");
            // See if the Obsolete attribute is defined for this method.
            bool isDef = Attribute.IsDefined(mInfo, typeof(ObsoleteAttribute));
            // Display the result.
            Console.WriteLine("The Obsolete Attribute {0} defined for {1} of class {2}.",
                isDef ? "is" : "is not", mInfo.Name, clsType.Name);
            // If it's defined, display the attribute's message.
            if (isDef)
            {
                ObsoleteAttribute obsAttr =
                                 (ObsoleteAttribute)Attribute.GetCustomAttribute(
                                                    mInfo, typeof(ObsoleteAttribute));
                if (obsAttr != null)
                    Console.WriteLine("The message is: \"{0}\".",
                        obsAttr.Message);
                else
                    Console.WriteLine("The message could not be retrieved.");
            }
        }
    }
}

/*
 * Output:
 * The Obsolete Attribute is defined for Method1 of class TestClass.
 * The message is: "This method is obsolete. Use Method2 instead.".
 */
open System

type TestClass() =
    // Assign the Obsolete attribute to a method.
    [<Obsolete "This method is obsolete. Use Method2 instead.">]
    member _.Method1() = ()
    member _.Method2() = ()

// Get the class type to access its metadata.
let clsType = typeof<TestClass>

// Get the MethodInfo object for Method1.
let mInfo = clsType.GetMethod "Method1"

// See if the Obsolete attribute is defined for this method.
let isDef = Attribute.IsDefined(mInfo, typeof<ObsoleteAttribute>)

// Display the result.
printfn $"""The Obsolete Attribute {if isDef then "is" else "is not"} defined for {mInfo.Name} of class {clsType.Name}."""

// If it's defined, display the attribute's message.
if isDef then
    let obsAttr =
        Attribute.GetCustomAttribute(mInfo, typeof<ObsoleteAttribute>)
        :?> ObsoleteAttribute
    if obsAttr <> null then
        printfn $"The message is: \"{obsAttr.Message}\"."
    else
        printfn "The message could not be retrieved."

// Output:
//  The Obsolete Attribute is defined for Method1 of class TestClass.
// The message is: "This method is obsolete. Use Method2 instead.".
Imports System.Reflection

Module DemoModule

    Public Class TestClass
        ' Assign the Obsolete attribute to a method.
        <Obsolete("This method is obsolete. Use Method2() instead.")> _
        Public Sub Method1()
        End Sub

        Public Sub Method2()
        End Sub
    End Class

    Sub Main()
        ' Get the class type to access its metadata.
        Dim clsType As Type = GetType(TestClass)
        ' Get the MethodInfo object for Method1.
        Dim mInfo As MethodInfo = clsType.GetMethod("Method1")
        ' See if the Obsolete attribute is defined for this method.
        Dim isDef As Boolean = Attribute.IsDefined(mInfo, _
            GetType(ObsoleteAttribute))
        Dim strDef As String
        If isDef = True Then
            strDef = "is"
        Else
            strDef = "is not"
        End If
        ' Display the results.
        Console.WriteLine("The Obsolete attribute {0} defined for " & _
            "method {1} of class {2}.", strDef, mInfo.Name, clsType.Name)
        ' If it's defined, display the attribute's message.
        If isDef = True Then
            Dim attr As Attribute = Attribute.GetCustomAttribute(mInfo, _
                GetType(ObsoleteAttribute))
            If Not attr Is Nothing And TypeOf attr Is ObsoleteAttribute Then
                Dim obsAttr As ObsoleteAttribute = _
                    CType(attr, ObsoleteAttribute)
                Console.WriteLine("The message is: ""{0}""", obsAttr.Message)
            Else
                Console.WriteLine("The message could not be retrieved.")
            End If
        End If
    End Sub
End Module

' Output:
' The Obsolete attribute is defined for method Method1 of class TestClass.
' The message is: "This method is obsolete. Use Method2() instead."

Açıklamalar

Not

.NET Framework sürüm 2.0'dan başlayarak, öznitelikler yeni meta veri biçiminde depolanıyorsa bu yöntem türler, yöntemler ve oluşturucular üzerindeki güvenlik özniteliklerini döndürür. Sürüm 2.0 veya üzeri ile derlenen derlemeler yeni biçimi kullanır. .NET Framework önceki sürümleriyle derlenen dinamik derlemeler ve derlemeler eski XML biçimini kullanır. Bkz. Bildirim Temelli Güvenlik Özniteliklerini Yayma.

Şunlara uygulanır

GetCustomAttribute(Assembly, Type, Boolean)

Derlemeye uygulanan özel bir özniteliği alır. Parametreler derlemeyi, aranacak özel özniteliğin türünü ve yoksayılan arama seçeneğini belirtir.

public:
 static Attribute ^ GetCustomAttribute(System::Reflection::Assembly ^ element, Type ^ attributeType, bool inherit);
public static Attribute? GetCustomAttribute (System.Reflection.Assembly element, Type attributeType, bool inherit);
public static Attribute GetCustomAttribute (System.Reflection.Assembly element, Type attributeType, bool inherit);
static member GetCustomAttribute : System.Reflection.Assembly * Type * bool -> Attribute
Public Shared Function GetCustomAttribute (element As Assembly, attributeType As Type, inherit As Boolean) As Attribute

Parametreler

element
Assembly

yeniden kullanılabilir bir modül koleksiyonunu açıklayan sınıfından türetilmiş Assembly bir nesne.

attributeType
Type

Aranacak özel özniteliğin türü veya temel türü.

inherit
Boolean

Bu parametre yoksayılır ve bu yöntemin çalışmasını etkilemez.

Döndürülenler

Attribute

türüne uygulanan elementtek bir özel özniteliğine attributeType başvuru veya null böyle bir öznitelik yoksa.

Özel durumlar

element veya attributeType şeklindedir null.

attributeType ' den Attributetüretilmemiştir.

İstenen özniteliklerden birden fazlası bulundu.

Örnekler

Aşağıdaki kod örneği, parametre olarak bir alan Assembly yönteminin GetCustomAttribute kullanımını göstermektedir.

using namespace System;
using namespace System::Reflection;

// Add an AssemblyDescription attribute
[assembly:AssemblyDescription("A sample description")];
namespace IsDef1CS
{
   ref class DemoClass
   {
   public:
      static void Main()
      {
         
         // Get the class type to access its metadata.
         Type^ clsType = DemoClass::typeid;
         
         // Get the assembly object.
         Assembly^ assy = clsType->Assembly;
         
         // Store the assembly's name.
         String^ assyName = assy->GetName()->Name;
         
         //Type assyType = assy.GetType();
         // See if the Assembly Description is defined.
         bool isdef = Attribute::IsDefined( assy, AssemblyDescriptionAttribute::typeid );
         if ( isdef )
         {
            
            // Affirm that the attribute is defined.
            Console::WriteLine( "The AssemblyDescription attribute "
            "is defined for assembly {0}.", assyName );
            
            // Get the description attribute itself.
            AssemblyDescriptionAttribute^ adAttr = dynamic_cast<AssemblyDescriptionAttribute^>(Attribute::GetCustomAttribute( assy, AssemblyDescriptionAttribute::typeid ));
            
            // Display the description.
            if ( adAttr != nullptr )
                        Console::WriteLine( "The description is \"{0}\".", adAttr->Description );
            else
                        Console::WriteLine( "The description could not "
            "be retrieved." );
         }
         else
                  Console::WriteLine( "The AssemblyDescription attribute is not "
         "defined for assembly {0}.", assyName );
      }

   };

}


/*
 * Output:
 * The AssemblyDescription attributeis defined for assembly IsDef1CS.
 * The description is "A sample description".
 */
using System;
using System.Reflection;

// Add an AssemblyDescription attribute
[assembly: AssemblyDescription("A sample description")]
namespace IsDef1CS
{
    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(DemoClass);
            // Get the assembly object.
            Assembly assy = clsType.Assembly;
            // Store the assembly's name.
            String assyName = assy.GetName().Name;
            // See if the Assembly Description is defined.
            bool isdef = Attribute.IsDefined(assy,
                typeof(AssemblyDescriptionAttribute));
            if (isdef)
            {
                // Affirm that the attribute is defined.
                Console.WriteLine("The AssemblyDescription attribute " +
                    "is defined for assembly {0}.", assyName);
                // Get the description attribute itself.
                AssemblyDescriptionAttribute adAttr =
                    (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(
                    assy, typeof(AssemblyDescriptionAttribute));
                // Display the description.
                if (adAttr != null)
                    Console.WriteLine("The description is \"{0}\".",
                        adAttr.Description);
                else
                    Console.WriteLine("The description could not " +
                        "be retrieved.");
            }
            else
                Console.WriteLine("The AssemblyDescription attribute is not " +
                    "defined for assembly {0}.", assyName);
        }
    }
}

/*
 * Output:
 * The AssemblyDescription attribute is defined for assembly IsDef1CS.
 * The description is "A sample description".
 */
open System
open System.Reflection

// Add an AssemblyDescription attribute
[<assembly: AssemblyDescription "A sample description">]
do ()

type DemoClass = class end

// Get the class type to access its metadata.
let clsType = typeof<DemoClass>

// Get the assembly object.
let assembly = clsType.Assembly;

// Store the assembly's name.
let assemblyName = assembly.GetName().Name

// See if the Assembly Description is defined.
let isdef = 
    Attribute.IsDefined(assembly, typeof<AssemblyDescriptionAttribute>)

if isdef then
    // Affirm that the attribute is defined.
    printfn $"The AssemblyDescription attribute is defined for assembly {assemblyName}."
    
    // Get the description attribute itself.
    let adAttr =
        Attribute.GetCustomAttribute(assembly, typeof<AssemblyDescriptionAttribute>)
        :?> AssemblyDescriptionAttribute

    // Display the description.
    if adAttr <> null then
        printfn $"The description is \"{adAttr.Description}\"."
    else
        printfn $"The description could not be retrieved."
else
    printfn $"The AssemblyDescription attribute is not defined for assembly {assemblyName}."

// Output:
//  The AssemblyDescription attribute is defined for assembly IsDef1FS.
//  The description is "A sample description".
Imports System.Reflection

' Add an AssemblyDescription attribute.
<Assembly: AssemblyDescription("A sample description")> 

Module DemoModule
    Sub Main()
        ' Get the assembly for this module.
        Dim assy As System.Reflection.Assembly = GetType(DemoModule).Assembly
        ' Store the assembly name.
        Dim assyName As String = assy.GetName().Name
        ' See if the AssemblyDescription attribute is defined.
        If Attribute.IsDefined(assy, GetType(AssemblyDescriptionAttribute)) _
            Then
            ' Affirm that the attribute is defined. Assume the filename of
            ' this code example is "IsDef1VB".
            Console.WriteLine("The AssemblyDescription attribute is " & _
                "defined for assembly {0}.", assyName)
            ' Get the description attribute itself.
            Dim attr As Attribute = Attribute.GetCustomAttribute( _
                assy, GetType(AssemblyDescriptionAttribute))
            ' Display the description.
            If Not attr Is Nothing And _
                TypeOf attr Is AssemblyDescriptionAttribute Then
                Dim adAttr As AssemblyDescriptionAttribute = _
                    CType(attr, AssemblyDescriptionAttribute)
                Console.WriteLine("The description is " & _
                    Chr(34) & "{0}" & Chr(34) & ".", adAttr.Description)
            Else
                Console.WriteLine("The description could not be retrieved.")
            End If
        Else
            Console.WriteLine("The AssemblyDescription attribute is not " & _
                              "defined for assembly {0}.", assyName)
        End If
    End Sub
End Module

' Output:
' The AssemblyDescription attribute is defined for assembly IsDef1VB.
' The description is "A sample description".

Açıklamalar

Not

.NET Framework sürüm 2.0'dan başlayarak, öznitelikler yeni meta veri biçiminde depolanıyorsa bu yöntem güvenlik özniteliklerini döndürür. Sürüm 2.0 veya üzeri ile derlenen derlemeler yeni biçimi kullanır. .NET Framework önceki sürümleriyle derlenen dinamik derlemeler ve derlemeler eski XML biçimini kullanır. Bkz. Bildirim Temelli Güvenlik Özniteliklerini Yayma.

Şunlara uygulanır

GetCustomAttribute(Module, Type, Boolean)

Modüle uygulanan özel bir özniteliği alır. Parametreler modülü, aranacak özel özniteliğin türünü ve yoksayılan arama seçeneğini belirtir.

public:
 static Attribute ^ GetCustomAttribute(System::Reflection::Module ^ element, Type ^ attributeType, bool inherit);
public static Attribute? GetCustomAttribute (System.Reflection.Module element, Type attributeType, bool inherit);
public static Attribute GetCustomAttribute (System.Reflection.Module element, Type attributeType, bool inherit);
static member GetCustomAttribute : System.Reflection.Module * Type * bool -> Attribute
Public Shared Function GetCustomAttribute (element As Module, attributeType As Type, inherit As Boolean) As Attribute

Parametreler

element
Module

Sınıfından Module türetilen ve taşınabilir yürütülebilir dosyayı açıklayan nesne.

attributeType
Type

Aranacak özel özniteliğin türü veya temel türü.

inherit
Boolean

Bu parametre yoksayılır ve bu yöntemin çalışmasını etkilemez.

Döndürülenler

Attribute

türüne uygulanan veya null böyle bir öznitelik yoksa türündeki attributeType tek özel özniteliğe elementbaşvuru.

Özel durumlar

element veya attributeType şeklindedir null.

attributeType , 'den Attributetüretilmemiştir.

İstenen özniteliklerden birden fazlası bulundu.

Örnekler

Aşağıdaki kod örneği, parametre olarak bir alan Module yönteminin GetCustomAttribute kullanımını gösterir.

using namespace System;
using namespace System::Diagnostics;

// Add the Debuggable attribute to the module.
[module:Debuggable(true,false)];
namespace IsDef2CS
{
   ref class DemoClass
   {
   public:
      static void Main()
      {
         
         // Get the class type to access its metadata.
         Type^ clsType = DemoClass::typeid;
         
         // See if the Debuggable attribute is defined for this module.
         bool isDef = Attribute::IsDefined( clsType->Module, DebuggableAttribute::typeid );
         
         // Display the result.
         Console::WriteLine( "The Debuggable attribute {0} "
         "defined for Module {1}.", isDef ? (String^)"is" : "is not", clsType->Module->Name );
         
         // If the attribute is defined, display the JIT settings.
         if ( isDef )
         {
            
            // Retrieve the attribute itself.
            DebuggableAttribute^ dbgAttr = dynamic_cast<DebuggableAttribute^>(Attribute::GetCustomAttribute( clsType->Module, DebuggableAttribute::typeid ));
            if ( dbgAttr != nullptr )
            {
               Console::WriteLine( "JITTrackingEnabled is {0}.", dbgAttr->IsJITTrackingEnabled );
               Console::WriteLine( "JITOptimizerDisabled is {0}.", dbgAttr->IsJITOptimizerDisabled );
            }
            else
                        Console::WriteLine( "The Debuggable attribute "
            "could not be retrieved." );
         }
      }

   };

}


/*
 * Output:
 * The Debuggable attribute is defined for Module IsDef2CS.exe.
 * JITTrackingEnabled is True.
 * JITOptimizerDisabled is False.
 */
using System;
using System.Diagnostics;

// Add the Debuggable attribute to the module.
[module:Debuggable(true, false)]
namespace IsDef2CS
{
    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(DemoClass);
            // See if the Debuggable attribute is defined for this module.
            bool isDef = Attribute.IsDefined(clsType.Module,
                typeof(DebuggableAttribute));
            // Display the result.
            Console.WriteLine("The Debuggable attribute {0} " +
                "defined for Module {1}.",
                isDef ? "is" : "is not",
                clsType.Module.Name);
            // If the attribute is defined, display the JIT settings.
            if (isDef)
            {
                // Retrieve the attribute itself.
                DebuggableAttribute dbgAttr = (DebuggableAttribute)
                    Attribute.GetCustomAttribute(clsType.Module,
                    typeof(DebuggableAttribute));
                if (dbgAttr != null)
                {
                    Console.WriteLine("JITTrackingEnabled is {0}.",
                        dbgAttr.IsJITTrackingEnabled);
                    Console.WriteLine("JITOptimizerDisabled is {0}.",
                        dbgAttr.IsJITOptimizerDisabled);
                }
                else
                    Console.WriteLine("The Debuggable attribute " +
                        "could not be retrieved.");
            }
        }
    }
}

/*
 * Output:
 * The Debuggable attribute is defined for Module IsDef2CS.exe.
 * JITTrackingEnabled is True.
 * JITOptimizerDisabled is False.
 */
open System
open System.Diagnostics

// Add the Debuggable attribute to the module.
[<``module``: Debuggable(true, false)>]
do ()
    
type DemoClass = class end

// Get the class type to access its metadata.
let clsType = typeof<DemoClass>

// See if the Debuggable attribute is defined for this module.
let isDef = Attribute.IsDefined(clsType.Module, typeof<DebuggableAttribute>)

// Display the result.
printfn $"""The Debuggable attribute {if isDef then "is" else "is not"} defined for Module {clsType.Module.Name}."""

// If the attribute is defined, display the JIT settings.
if isDef then
    // Retrieve the attribute itself.
    let dbgAttr =
        Attribute.GetCustomAttribute(clsType.Module, typeof<DebuggableAttribute>)
        :?> DebuggableAttribute

    if dbgAttr <> null then
        printfn $"JITTrackingEnabled is {dbgAttr.IsJITTrackingEnabled}."
        printfn $"JITOptimizerDisabled is {dbgAttr.IsJITOptimizerDisabled}."            
    else
        printfn "The Debuggable attribute could not be retrieved."

// Output:
//  The Debuggable attribute is defined for Module IsDef2CS.exe.
//  JITTrackingEnabled is True.
//  JITOptimizerDisabled is False.
Imports System.Reflection
Imports System.Diagnostics

' Add the Debuggable attribute to the module.
<Module: Debuggable(True, False)> 

Module DemoModule
    Sub Main()
        ' Get the module type information to access its metadata.
        Dim modType As Type = GetType(DemoModule)
        ' See if the Debuggable attribute is defined.
        Dim isDef As Boolean = Attribute.IsDefined(modType.Module, _
                               GetType(DebuggableAttribute))
        Dim strDef As String
        If isDef = True Then
            strDef = "is"
        Else
            strDef = "is not"
        End If
        ' Display the result
        Console.WriteLine("The debuggable attribute {0} defined for " & _
                          "module {1}.", strDef, modType.Name)
        ' If the attribute is defined, display the JIT settings.
        If isDef = True Then
            ' Retrieve the attribute itself.
            Dim attr As Attribute = _
                Attribute.GetCustomAttribute(modType.Module, _
                GetType(DebuggableAttribute))
            If Not attr Is Nothing And TypeOf attr Is DebuggableAttribute Then
                Dim dbgAttr As DebuggableAttribute = _
                    CType(attr, DebuggableAttribute)
                Console.WriteLine("JITTrackingEnabled is {0}.", _
                    dbgAttr.IsJITTrackingEnabled.ToString())
                Console.WriteLine("JITOptimizerDisabled is {0}.", _
                    dbgAttr.IsJITOptimizerDisabled.ToString())
            Else
                Console.WriteLine("The Debuggable attribute could " & _
                                  "not be retrieved.")
            End If
        End If
    End Sub
End Module

' Output:
' The debuggable attribute is defined for module DemoModule.
' JITTrackingEnabled is True.
' JITOptimizerDisabled is False.

Şunlara uygulanır

GetCustomAttribute(Module, Type)

Modüle uygulanan özel bir özniteliği alır. Parametreler modülü ve aranacak özel özniteliğin türünü belirtir.

public:
 static Attribute ^ GetCustomAttribute(System::Reflection::Module ^ element, Type ^ attributeType);
public static Attribute? GetCustomAttribute (System.Reflection.Module element, Type attributeType);
public static Attribute GetCustomAttribute (System.Reflection.Module element, Type attributeType);
static member GetCustomAttribute : System.Reflection.Module * Type -> Attribute
Public Shared Function GetCustomAttribute (element As Module, attributeType As Type) As Attribute

Parametreler

element
Module

Sınıfından Module türetilen ve taşınabilir yürütülebilir dosyayı açıklayan bir nesne.

attributeType
Type

Aranacak özel özniteliğin türü veya temel türü.

Döndürülenler

Attribute

türüne uygulanan elementtek bir özel özniteliğine attributeType başvuru veya null böyle bir öznitelik yoksa.

Özel durumlar

element veya attributeType şeklindedir null.

attributeType ' den Attributetüretilmemiştir.

İstenen özniteliklerden birden fazlası bulundu.

Örnekler

Aşağıdaki kod örneği, parametre olarak bir alan Module yönteminin GetCustomAttribute kullanımını gösterir.

using namespace System;
using namespace System::Diagnostics;

// Add the Debuggable attribute to the module.
[module:Debuggable(true,false)];
namespace IsDef2CS
{
   ref class DemoClass
   {
   public:
      static void Main()
      {
         
         // Get the class type to access its metadata.
         Type^ clsType = DemoClass::typeid;
         
         // See if the Debuggable attribute is defined for this module.
         bool isDef = Attribute::IsDefined( clsType->Module, DebuggableAttribute::typeid );
         
         // Display the result.
         Console::WriteLine( "The Debuggable attribute {0} "
         "defined for Module {1}.", isDef ? (String^)"is" : "is not", clsType->Module->Name );
         
         // If the attribute is defined, display the JIT settings.
         if ( isDef )
         {
            
            // Retrieve the attribute itself.
            DebuggableAttribute^ dbgAttr = dynamic_cast<DebuggableAttribute^>(Attribute::GetCustomAttribute( clsType->Module, DebuggableAttribute::typeid ));
            if ( dbgAttr != nullptr )
            {
               Console::WriteLine( "JITTrackingEnabled is {0}.", dbgAttr->IsJITTrackingEnabled );
               Console::WriteLine( "JITOptimizerDisabled is {0}.", dbgAttr->IsJITOptimizerDisabled );
            }
            else
                        Console::WriteLine( "The Debuggable attribute "
            "could not be retrieved." );
         }
      }

   };

}


/*
 * Output:
 * The Debuggable attribute is defined for Module IsDef2CS.exe.
 * JITTrackingEnabled is True.
 * JITOptimizerDisabled is False.
 */
using System;
using System.Diagnostics;

// Add the Debuggable attribute to the module.
[module:Debuggable(true, false)]
namespace IsDef2CS
{
    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(DemoClass);
            // See if the Debuggable attribute is defined for this module.
            bool isDef = Attribute.IsDefined(clsType.Module,
                typeof(DebuggableAttribute));
            // Display the result.
            Console.WriteLine("The Debuggable attribute {0} " +
                "defined for Module {1}.",
                isDef ? "is" : "is not",
                clsType.Module.Name);
            // If the attribute is defined, display the JIT settings.
            if (isDef)
            {
                // Retrieve the attribute itself.
                DebuggableAttribute dbgAttr = (DebuggableAttribute)
                    Attribute.GetCustomAttribute(clsType.Module,
                    typeof(DebuggableAttribute));
                if (dbgAttr != null)
                {
                    Console.WriteLine("JITTrackingEnabled is {0}.",
                        dbgAttr.IsJITTrackingEnabled);
                    Console.WriteLine("JITOptimizerDisabled is {0}.",
                        dbgAttr.IsJITOptimizerDisabled);
                }
                else
                    Console.WriteLine("The Debuggable attribute " +
                        "could not be retrieved.");
            }
        }
    }
}

/*
 * Output:
 * The Debuggable attribute is defined for Module IsDef2CS.exe.
 * JITTrackingEnabled is True.
 * JITOptimizerDisabled is False.
 */
open System
open System.Diagnostics

// Add the Debuggable attribute to the module.
[<``module``: Debuggable(true, false)>]
do ()
    
type DemoClass = class end

// Get the class type to access its metadata.
let clsType = typeof<DemoClass>

// See if the Debuggable attribute is defined for this module.
let isDef = Attribute.IsDefined(clsType.Module, typeof<DebuggableAttribute>)

// Display the result.
printfn $"""The Debuggable attribute {if isDef then "is" else "is not"} defined for Module {clsType.Module.Name}."""

// If the attribute is defined, display the JIT settings.
if isDef then
    // Retrieve the attribute itself.
    let dbgAttr =
        Attribute.GetCustomAttribute(clsType.Module, typeof<DebuggableAttribute>)
        :?> DebuggableAttribute

    if dbgAttr <> null then
        printfn $"JITTrackingEnabled is {dbgAttr.IsJITTrackingEnabled}."
        printfn $"JITOptimizerDisabled is {dbgAttr.IsJITOptimizerDisabled}."            
    else
        printfn "The Debuggable attribute could not be retrieved."

// Output:
//  The Debuggable attribute is defined for Module IsDef2CS.exe.
//  JITTrackingEnabled is True.
//  JITOptimizerDisabled is False.
Imports System.Reflection
Imports System.Diagnostics

' Add the Debuggable attribute to the module.
<Module: Debuggable(True, False)> 

Module DemoModule
    Sub Main()
        ' Get the module type information to access its metadata.
        Dim modType As Type = GetType(DemoModule)
        ' See if the Debuggable attribute is defined.
        Dim isDef As Boolean = Attribute.IsDefined(modType.Module, _
                               GetType(DebuggableAttribute))
        Dim strDef As String
        If isDef = True Then
            strDef = "is"
        Else
            strDef = "is not"
        End If
        ' Display the result
        Console.WriteLine("The debuggable attribute {0} defined for " & _
                          "module {1}.", strDef, modType.Name)
        ' If the attribute is defined, display the JIT settings.
        If isDef = True Then
            ' Retrieve the attribute itself.
            Dim attr As Attribute = _
                Attribute.GetCustomAttribute(modType.Module, _
                GetType(DebuggableAttribute))
            If Not attr Is Nothing And TypeOf attr Is DebuggableAttribute Then
                Dim dbgAttr As DebuggableAttribute = _
                    CType(attr, DebuggableAttribute)
                Console.WriteLine("JITTrackingEnabled is {0}.", _
                    dbgAttr.IsJITTrackingEnabled.ToString())
                Console.WriteLine("JITOptimizerDisabled is {0}.", _
                    dbgAttr.IsJITOptimizerDisabled.ToString())
            Else
                Console.WriteLine("The Debuggable attribute could " & _
                                  "not be retrieved.")
            End If
        End If
    End Sub
End Module

' Output:
' The debuggable attribute is defined for module DemoModule.
' JITTrackingEnabled is True.
' JITOptimizerDisabled is False.

Şunlara uygulanır

GetCustomAttribute(MemberInfo, Type)

Türün bir üyesine uygulanan özel bir özniteliği alır. Parametreler, üyeyi ve aranacak özel özniteliğin türünü belirtir.

public:
 static Attribute ^ GetCustomAttribute(System::Reflection::MemberInfo ^ element, Type ^ attributeType);
public static Attribute? GetCustomAttribute (System.Reflection.MemberInfo element, Type attributeType);
public static Attribute GetCustomAttribute (System.Reflection.MemberInfo element, Type attributeType);
static member GetCustomAttribute : System.Reflection.MemberInfo * Type -> Attribute
Public Shared Function GetCustomAttribute (element As MemberInfo, attributeType As Type) As Attribute

Parametreler

element
MemberInfo

Bir sınıfın oluşturucu, MemberInfo olay, alan, yöntem veya özellik üyesini tanımlayan sınıfından türetilen nesne.

attributeType
Type

Aranacak özel özniteliğin türü veya temel türü.

Döndürülenler

Attribute

türüne uygulanan elementtek bir özel özniteliğine attributeType başvuru veya null böyle bir öznitelik yoksa.

Özel durumlar

element veya attributeType şeklindedir null.

attributeType ' den Attributetüretilmemiştir.

element oluşturucu, yöntem, özellik, olay, tür veya alan değildir.

İstenen özniteliklerden birden fazlası bulundu.

Özel öznitelik türü yüklenemiyor.

Örnekler

Aşağıdaki kod örneği, parametre olarak bir alan MemberInfo yönteminin GetCustomAttribute kullanımını gösterir.

using namespace System;
using namespace System::Reflection;

namespace IsDef4CS
{
   public ref class TestClass
   {
   public:

      // Assign the Obsolete attribute to a method.

      [Obsolete("This method is obsolete. Use Method2 instead.")]
      void Method1(){}

      void Method2(){}

   };

   ref class DemoClass
   {
   public:
      static void Main()
      {
         
         // Get the class type to access its metadata.
         Type^ clsType = TestClass::typeid;
         
         // Get the MethodInfo object for Method1.
         MethodInfo^ mInfo = clsType->GetMethod( "Method1" );
         
         // See if the Obsolete attribute is defined for this method.
         bool isDef = Attribute::IsDefined( mInfo, ObsoleteAttribute::typeid );
         
         // Display the result.
         Console::WriteLine( "The Obsolete Attribute {0} defined for {1} of class {2}.", isDef ? (String^)"is" : "is not", mInfo->Name, clsType->Name );
         
         // If it's defined, display the attribute's message.
         if ( isDef )
         {
            ObsoleteAttribute^ obsAttr = dynamic_cast<ObsoleteAttribute^>(Attribute::GetCustomAttribute( mInfo, ObsoleteAttribute::typeid ));
            if ( obsAttr != nullptr )
                        Console::WriteLine( "The message is: \"{0}\".", obsAttr->Message );
            else
                        Console::WriteLine( "The message could not be retrieved." );
         }
      }

   };

}


/*
 * Output:
 * The Obsolete Attribute is defined for Method1 of class TestClass.
 * The message is: "This method is obsolete. Use Method2 instead.".
 */
using System;
using System.Reflection;

namespace IsDef4CS
{
    public class TestClass
    {
        // Assign the Obsolete attribute to a method.
        [Obsolete("This method is obsolete. Use Method2 instead.")]
        public void Method1()
        {}
        public void Method2()
        {}
    }

    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(TestClass);
            // Get the MethodInfo object for Method1.
            MethodInfo mInfo = clsType.GetMethod("Method1");
            // See if the Obsolete attribute is defined for this method.
            bool isDef = Attribute.IsDefined(mInfo, typeof(ObsoleteAttribute));
            // Display the result.
            Console.WriteLine("The Obsolete Attribute {0} defined for {1} of class {2}.",
                isDef ? "is" : "is not", mInfo.Name, clsType.Name);
            // If it's defined, display the attribute's message.
            if (isDef)
            {
                ObsoleteAttribute obsAttr =
                                 (ObsoleteAttribute)Attribute.GetCustomAttribute(
                                                    mInfo, typeof(ObsoleteAttribute));
                if (obsAttr != null)
                    Console.WriteLine("The message is: \"{0}\".",
                        obsAttr.Message);
                else
                    Console.WriteLine("The message could not be retrieved.");
            }
        }
    }
}

/*
 * Output:
 * The Obsolete Attribute is defined for Method1 of class TestClass.
 * The message is: "This method is obsolete. Use Method2 instead.".
 */
open System

type TestClass() =
    // Assign the Obsolete attribute to a method.
    [<Obsolete "This method is obsolete. Use Method2 instead.">]
    member _.Method1() = ()
    member _.Method2() = ()

// Get the class type to access its metadata.
let clsType = typeof<TestClass>

// Get the MethodInfo object for Method1.
let mInfo = clsType.GetMethod "Method1"

// See if the Obsolete attribute is defined for this method.
let isDef = Attribute.IsDefined(mInfo, typeof<ObsoleteAttribute>)

// Display the result.
printfn $"""The Obsolete Attribute {if isDef then "is" else "is not"} defined for {mInfo.Name} of class {clsType.Name}."""

// If it's defined, display the attribute's message.
if isDef then
    let obsAttr =
        Attribute.GetCustomAttribute(mInfo, typeof<ObsoleteAttribute>)
        :?> ObsoleteAttribute
    if obsAttr <> null then
        printfn $"The message is: \"{obsAttr.Message}\"."
    else
        printfn "The message could not be retrieved."

// Output:
//  The Obsolete Attribute is defined for Method1 of class TestClass.
// The message is: "This method is obsolete. Use Method2 instead.".
Imports System.Reflection

Module DemoModule

    Public Class TestClass
        ' Assign the Obsolete attribute to a method.
        <Obsolete("This method is obsolete. Use Method2() instead.")> _
        Public Sub Method1()
        End Sub

        Public Sub Method2()
        End Sub
    End Class

    Sub Main()
        ' Get the class type to access its metadata.
        Dim clsType As Type = GetType(TestClass)
        ' Get the MethodInfo object for Method1.
        Dim mInfo As MethodInfo = clsType.GetMethod("Method1")
        ' See if the Obsolete attribute is defined for this method.
        Dim isDef As Boolean = Attribute.IsDefined(mInfo, _
            GetType(ObsoleteAttribute))
        Dim strDef As String
        If isDef = True Then
            strDef = "is"
        Else
            strDef = "is not"
        End If
        ' Display the results.
        Console.WriteLine("The Obsolete attribute {0} defined for " & _
            "method {1} of class {2}.", strDef, mInfo.Name, clsType.Name)
        ' If it's defined, display the attribute's message.
        If isDef = True Then
            Dim attr As Attribute = Attribute.GetCustomAttribute(mInfo, _
                GetType(ObsoleteAttribute))
            If Not attr Is Nothing And TypeOf attr Is ObsoleteAttribute Then
                Dim obsAttr As ObsoleteAttribute = _
                    CType(attr, ObsoleteAttribute)
                Console.WriteLine("The message is: ""{0}""", obsAttr.Message)
            Else
                Console.WriteLine("The message could not be retrieved.")
            End If
        End If
    End Sub
End Module

' Output:
' The Obsolete attribute is defined for method Method1 of class TestClass.
' The message is: "This method is obsolete. Use Method2() instead."

Açıklamalar

Eşleşme, değerinin Dönüş Değeri bölümünde Type.IsAssignableFromaçıklanan şekilde belirlenir.

Not

.NET Framework sürüm 2.0'dan başlayarak, öznitelikler yeni meta veri biçiminde depolanıyorsa bu yöntem türler, yöntemler ve oluşturucular üzerindeki güvenlik özniteliklerini döndürür. Sürüm 2.0 veya üzeri ile derlenen derlemeler yeni biçimi kullanır. .NET Framework önceki sürümleriyle derlenen dinamik derlemeler ve derlemeler eski XML biçimini kullanır. Bkz. Bildirim Temelli Güvenlik Özniteliklerini Yayma.

Şunlara uygulanır

GetCustomAttribute(Assembly, Type)

Belirtilen derlemeye uygulanan özel bir özniteliği alır. Parametreler, aranacak özel özniteliğin derlemesini ve türünü belirtir.

public:
 static Attribute ^ GetCustomAttribute(System::Reflection::Assembly ^ element, Type ^ attributeType);
public static Attribute? GetCustomAttribute (System.Reflection.Assembly element, Type attributeType);
public static Attribute GetCustomAttribute (System.Reflection.Assembly element, Type attributeType);
static member GetCustomAttribute : System.Reflection.Assembly * Type -> Attribute
Public Shared Function GetCustomAttribute (element As Assembly, attributeType As Type) As Attribute

Parametreler

element
Assembly

yeniden kullanılabilir bir modül koleksiyonunu açıklayan sınıfından türetilmiş Assembly bir nesne.

attributeType
Type

Aranacak özel özniteliğin türü veya temel türü.

Döndürülenler

Attribute

türüne uygulanan elementtek bir özel özniteliğine attributeType başvuru veya null böyle bir öznitelik yoksa.

Özel durumlar

element veya attributeType şeklindedir null.

attributeType ' den Attributetüretilmemiştir.

İstenen özniteliklerden birden fazlası bulundu.

Örnekler

Aşağıdaki kod örneği, parametre olarak bir alan Assembly yönteminin GetCustomAttribute kullanımını göstermektedir.

using namespace System;
using namespace System::Reflection;

// Add an AssemblyDescription attribute
[assembly:AssemblyDescription("A sample description")];
namespace IsDef1CS
{
   ref class DemoClass
   {
   public:
      static void Main()
      {
         
         // Get the class type to access its metadata.
         Type^ clsType = DemoClass::typeid;
         
         // Get the assembly object.
         Assembly^ assy = clsType->Assembly;
         
         // Store the assembly's name.
         String^ assyName = assy->GetName()->Name;
         
         //Type assyType = assy.GetType();
         // See if the Assembly Description is defined.
         bool isdef = Attribute::IsDefined( assy, AssemblyDescriptionAttribute::typeid );
         if ( isdef )
         {
            
            // Affirm that the attribute is defined.
            Console::WriteLine( "The AssemblyDescription attribute "
            "is defined for assembly {0}.", assyName );
            
            // Get the description attribute itself.
            AssemblyDescriptionAttribute^ adAttr = dynamic_cast<AssemblyDescriptionAttribute^>(Attribute::GetCustomAttribute( assy, AssemblyDescriptionAttribute::typeid ));
            
            // Display the description.
            if ( adAttr != nullptr )
                        Console::WriteLine( "The description is \"{0}\".", adAttr->Description );
            else
                        Console::WriteLine( "The description could not "
            "be retrieved." );
         }
         else
                  Console::WriteLine( "The AssemblyDescription attribute is not "
         "defined for assembly {0}.", assyName );
      }

   };

}


/*
 * Output:
 * The AssemblyDescription attributeis defined for assembly IsDef1CS.
 * The description is "A sample description".
 */
using System;
using System.Reflection;

// Add an AssemblyDescription attribute
[assembly: AssemblyDescription("A sample description")]
namespace IsDef1CS
{
    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(DemoClass);
            // Get the assembly object.
            Assembly assy = clsType.Assembly;
            // Store the assembly's name.
            String assyName = assy.GetName().Name;
            // See if the Assembly Description is defined.
            bool isdef = Attribute.IsDefined(assy,
                typeof(AssemblyDescriptionAttribute));
            if (isdef)
            {
                // Affirm that the attribute is defined.
                Console.WriteLine("The AssemblyDescription attribute " +
                    "is defined for assembly {0}.", assyName);
                // Get the description attribute itself.
                AssemblyDescriptionAttribute adAttr =
                    (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(
                    assy, typeof(AssemblyDescriptionAttribute));
                // Display the description.
                if (adAttr != null)
                    Console.WriteLine("The description is \"{0}\".",
                        adAttr.Description);
                else
                    Console.WriteLine("The description could not " +
                        "be retrieved.");
            }
            else
                Console.WriteLine("The AssemblyDescription attribute is not " +
                    "defined for assembly {0}.", assyName);
        }
    }
}

/*
 * Output:
 * The AssemblyDescription attribute is defined for assembly IsDef1CS.
 * The description is "A sample description".
 */
open System
open System.Reflection

// Add an AssemblyDescription attribute
[<assembly: AssemblyDescription "A sample description">]
do ()

type DemoClass = class end

// Get the class type to access its metadata.
let clsType = typeof<DemoClass>

// Get the assembly object.
let assembly = clsType.Assembly;

// Store the assembly's name.
let assemblyName = assembly.GetName().Name

// See if the Assembly Description is defined.
let isdef = 
    Attribute.IsDefined(assembly, typeof<AssemblyDescriptionAttribute>)

if isdef then
    // Affirm that the attribute is defined.
    printfn $"The AssemblyDescription attribute is defined for assembly {assemblyName}."
    
    // Get the description attribute itself.
    let adAttr =
        Attribute.GetCustomAttribute(assembly, typeof<AssemblyDescriptionAttribute>)
        :?> AssemblyDescriptionAttribute

    // Display the description.
    if adAttr <> null then
        printfn $"The description is \"{adAttr.Description}\"."
    else
        printfn $"The description could not be retrieved."
else
    printfn $"The AssemblyDescription attribute is not defined for assembly {assemblyName}."

// Output:
//  The AssemblyDescription attribute is defined for assembly IsDef1FS.
//  The description is "A sample description".
Imports System.Reflection

' Add an AssemblyDescription attribute.
<Assembly: AssemblyDescription("A sample description")> 

Module DemoModule
    Sub Main()
        ' Get the assembly for this module.
        Dim assy As System.Reflection.Assembly = GetType(DemoModule).Assembly
        ' Store the assembly name.
        Dim assyName As String = assy.GetName().Name
        ' See if the AssemblyDescription attribute is defined.
        If Attribute.IsDefined(assy, GetType(AssemblyDescriptionAttribute)) _
            Then
            ' Affirm that the attribute is defined. Assume the filename of
            ' this code example is "IsDef1VB".
            Console.WriteLine("The AssemblyDescription attribute is " & _
                "defined for assembly {0}.", assyName)
            ' Get the description attribute itself.
            Dim attr As Attribute = Attribute.GetCustomAttribute( _
                assy, GetType(AssemblyDescriptionAttribute))
            ' Display the description.
            If Not attr Is Nothing And _
                TypeOf attr Is AssemblyDescriptionAttribute Then
                Dim adAttr As AssemblyDescriptionAttribute = _
                    CType(attr, AssemblyDescriptionAttribute)
                Console.WriteLine("The description is " & _
                    Chr(34) & "{0}" & Chr(34) & ".", adAttr.Description)
            Else
                Console.WriteLine("The description could not be retrieved.")
            End If
        Else
            Console.WriteLine("The AssemblyDescription attribute is not " & _
                              "defined for assembly {0}.", assyName)
        End If
    End Sub
End Module

' Output:
' The AssemblyDescription attribute is defined for assembly IsDef1VB.
' The description is "A sample description".

Açıklamalar

Birden fazla değerin GetCustomAttributes döndürülmesini bekliyorsanız veya AmbiguousMatchException oluşturulacaksa yöntemini kullanın.

Not

.NET Framework sürüm 2.0'dan başlayarak, öznitelikler yeni meta veri biçiminde depolanıyorsa bu yöntem güvenlik özniteliklerini döndürür. Sürüm 2.0 veya üzeri ile derlenen derlemeler yeni biçimi kullanır. .NET Framework önceki sürümleriyle derlenen dinamik derlemeler ve derlemeler eski XML biçimini kullanır. Bkz. Bildirim Temelli Güvenlik Özniteliklerini Yayma.

Şunlara uygulanır

GetCustomAttribute(ParameterInfo, Type)

Yöntem parametresine uygulanan özel bir özniteliği alır. Parametreler yöntem parametresini ve aranacak özel özniteliğin türünü belirtir.

public:
 static Attribute ^ GetCustomAttribute(System::Reflection::ParameterInfo ^ element, Type ^ attributeType);
public static Attribute? GetCustomAttribute (System.Reflection.ParameterInfo element, Type attributeType);
public static Attribute GetCustomAttribute (System.Reflection.ParameterInfo element, Type attributeType);
static member GetCustomAttribute : System.Reflection.ParameterInfo * Type -> Attribute
Public Shared Function GetCustomAttribute (element As ParameterInfo, attributeType As Type) As Attribute

Parametreler

element
ParameterInfo

Sınıfın bir üyesinin ParameterInfo parametresini açıklayan sınıfından türetilmiş bir nesne.

attributeType
Type

Aranacak özel özniteliğin türü veya temel türü.

Döndürülenler

Attribute

türüne uygulanan elementtek bir özel özniteliğine attributeType başvuru veya null böyle bir öznitelik yoksa.

Özel durumlar

element veya attributeType şeklindedir null.

attributeType ' den Attributetüretilmemiştir.

İstenen özniteliklerden birden fazlası bulundu.

Özel öznitelik türü yüklenemiyor.

Örnekler

Aşağıdaki kod örneği özel parametre Attribute sınıfını tanımlar ve özel özniteliği türetilmiş bir sınıftaki bir yönteme ve türetilmiş sınıfın tabanına uygular. Örnekte öznitelikleri döndürmek için yönteminin kullanımı GetCustomAttribute gösterilmektedir.

// Example for the Attribute::GetCustomAttribute( ParameterInfo*, Type* ) 
// method.
using namespace System;
using namespace System::Collections;
using namespace System::Reflection;

namespace NDP_UE_CPP
{

   // Define a custom parameter attribute that takes a single message argument.

   [AttributeUsage(AttributeTargets::Parameter)]
   public ref class ArgumentUsageAttribute: public Attribute
   {
   protected:

      // usageMsg is storage for the attribute message.
      String^ usageMsg;

   public:

      // This is the attribute constructor.
      ArgumentUsageAttribute( String^ UsageMsg )
      {
         this->usageMsg = UsageMsg;
      }


      property String^ Message 
      {
         // This is the Message property for the attribute.
         String^ get()
         {
            return usageMsg;
         }

         void set( String^ value )
         {
            this->usageMsg = value;
         }
      }
   };

   public ref class BaseClass
   {
   public:

      // Assign an ArgumentUsage attribute to the strArray parameter.
      // Assign a ParamArray attribute to strList.
      virtual void TestMethod( [ArgumentUsage("Must pass an array here.")]array<String^>^strArray,
                               ...array<String^>^strList ){}
   };

   public ref class DerivedClass: public BaseClass
   {
   public:

      // Assign an ArgumentUsage attributes to the strList parameter.
      virtual void TestMethod( array<String^>^strArray, [ArgumentUsage(
      "Can pass a parameter list or array here.")]array<String^>^strList ) override {}
   };
}

int main()
{
   Console::WriteLine( "This example of Attribute::GetCustomAttribute( Param"
   "eterInfo*, Type* )\ngenerates the following output." );

   // Get the class type, and then get the MethodInfo object 
   // for TestMethod to access its metadata.
   Type^ clsType = NDP_UE_CPP::DerivedClass::typeid;
   MethodInfo^ mInfo = clsType->GetMethod( "TestMethod" );

   // Iterate through the ParameterInfo array for the method parameters.
   array<ParameterInfo^>^pInfoArray = mInfo->GetParameters();
   if ( pInfoArray != nullptr )
   {
      // This implements foreach( ParameterInfo* paramInfo in pInfoArray ).
      IEnumerator^ myEnum = pInfoArray->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         ParameterInfo^ paramInfo = safe_cast<ParameterInfo^>(myEnum->Current);

         // See if the ParamArray attribute is defined.
         bool isDef = Attribute::IsDefined( paramInfo, ParamArrayAttribute::typeid );
         if ( isDef )
                  Console::WriteLine( "\nThe ParamArray attribute is defined for \n"
         "parameter {0} of method {1}.", paramInfo->Name, mInfo->Name );

         // See if ParamUsageAttribute is defined.  
         // If so, display a message.
         NDP_UE_CPP::ArgumentUsageAttribute^ usageAttr = static_cast<NDP_UE_CPP::ArgumentUsageAttribute^>(Attribute::GetCustomAttribute( paramInfo, NDP_UE_CPP::ArgumentUsageAttribute::typeid ));
         if ( usageAttr != nullptr )
         {
            Console::WriteLine( "\nThe ArgumentUsage attribute is defined for \n"
            "parameter {0} of method {1}.", paramInfo->Name, mInfo->Name );
            Console::WriteLine( "\n    The usage "
            "message for {0} is:\n    \"{1}\".", paramInfo->Name, usageAttr->Message );
         }
      }
   }
   else
      Console::WriteLine( "The parameters information could "
   "not be retrieved for method {0}.", mInfo->Name );
}

/*
This example of Attribute::GetCustomAttribute( ParameterInfo*, Type* )
generates the following output.

The ArgumentUsage attribute is defined for
parameter strArray of method TestMethod.

    The usage message for strArray is:
    "Must pass an array here.".

The ParamArray attribute is defined for
parameter strList of method TestMethod.

The ArgumentUsage attribute is defined for
parameter strList of method TestMethod.

    The usage message for strList is:
    "Can pass a parameter list or array here.".
*/
// Example for the Attribute.GetCustomAttribute( ParameterInfo, Type ) method.
using System;
using System.Reflection;

namespace NDP_UE_CS
{
    // Define a custom parameter attribute that takes a single message argument.
    [AttributeUsage( AttributeTargets.Parameter )]
    public class ArgumentUsageAttribute : Attribute
    {
        // This is the attribute constructor.
        public ArgumentUsageAttribute( string UsageMsg )
        {
            this.usageMsg = UsageMsg;
        }

        // usageMsg is storage for the attribute message.
        protected string usageMsg;

        // This is the Message property for the attribute.
        public string Message
        {
            get { return usageMsg; }
            set { usageMsg = value; }
        }
    }

    public class BaseClass
    {
        // Assign an ArgumentUsage attribute to the strArray parameter.
        // Assign a ParamArray attribute to strList using the params keyword.
        public virtual void TestMethod(
            [ArgumentUsage("Must pass an array here.")]
            String[] strArray,
            params String[] strList)
        { }
    }

    public class DerivedClass : BaseClass
    {
        // Assign an ArgumentUsage attribute to the strList parameter.
        // Assign a ParamArray attribute to strList using the params keyword.
        public override void TestMethod(
            String[] strArray,
            [ArgumentUsage("Can pass a parameter list or array here.")]
            params String[] strList)
        { }
    }

    class CustomParamDemo
    {
        static void Main( )
        {
            Console.WriteLine(
                "This example of Attribute.GetCustomAttribute( Param" +
                "eterInfo, Type )\ngenerates the following output." );

            // Get the class type, and then get the MethodInfo object
            // for TestMethod to access its metadata.
            Type clsType = typeof( DerivedClass );
            MethodInfo mInfo = clsType.GetMethod("TestMethod");

            // Iterate through the ParameterInfo array for the method parameters.
            ParameterInfo[] pInfoArray = mInfo.GetParameters();
            if (pInfoArray != null)
            {
                foreach( ParameterInfo paramInfo in pInfoArray )
                {
                    // See if the ParamArray attribute is defined.
                    bool isDef = Attribute.IsDefined(
                        paramInfo, typeof(ParamArrayAttribute));

                    if( isDef )
                        Console.WriteLine(
                            "\nThe ParamArray attribute is defined " +
                            "for \nparameter {0} of method {1}.",
                            paramInfo.Name, mInfo.Name);

                    // See if ParamUsageAttribute is defined.
                    // If so, display a message.
                    ArgumentUsageAttribute usageAttr = (ArgumentUsageAttribute)
                        Attribute.GetCustomAttribute(
                            paramInfo, typeof(ArgumentUsageAttribute) );

                    if( usageAttr != null )
                    {
                        Console.WriteLine(
                            "\nThe ArgumentUsage attribute is defined " +
                            "for \nparameter {0} of method {1}.",
                            paramInfo.Name, mInfo.Name );

                        Console.WriteLine( "\n    The usage " +
                            "message for {0} is:\n    \"{1}\".",
                            paramInfo.Name, usageAttr.Message);
                    }
                }
            }
            else
                Console.WriteLine(
                    "The parameters information could not " +
                    "be retrieved for method {0}.", mInfo.Name);
        }
    }
}

/*
This example of Attribute.GetCustomAttribute( ParameterInfo, Type )
generates the following output.

The ArgumentUsage attribute is defined for
parameter strArray of method TestMethod.

    The usage message for strArray is:
    "Must pass an array here.".

The ParamArray attribute is defined for
parameter strList of method TestMethod.

The ArgumentUsage attribute is defined for
parameter strList of method TestMethod.

    The usage message for strList is:
    "Can pass a parameter list or array here.".
*/
open System
open System.Reflection

// Define a custom parameter attribute that takes a single message argument.
[<AttributeUsage(AttributeTargets.Parameter); AllowNullLiteral>]
type ArgumentUsageAttribute(usageMsg) =
    inherit Attribute()
    
    // This is the Message property for the attribute.
    member val Message = usageMsg with get, set

type BaseClass() =
    // Assign an ArgumentUsage attribute to the strArray parameter.
    // Assign a ParamArray attribute to strList.
    abstract member TestMethod: strArray: string[] * strList: string[] -> unit
    default _.TestMethod([<ArgumentUsage("Must pass an array here.")>] strArray, [<ParamArray>] strList) = ()

type DerivedClass() =
    inherit BaseClass()
    
    // Assign an ArgumentUsage attribute to the strList parameter.
    // Assign a ParamArray attribute to strList.
    override _.TestMethod(
        strArray,
        [<ArgumentUsage "Can pass a parameter list or array here."; ParamArray>] 
        strList) = ()

printfn "This example of Attribute.GetCustomAttribute( ParameterInfo, Type )\ngenerates the following output."

// Get the class type, and then get the MethodInfo object
// for TestMethod to access its metadata.
let clsType = typeof<DerivedClass>
let mInfo = clsType.GetMethod "TestMethod"

// Iterate through the ParameterInfo array for the method parameters.
let pInfoArray = mInfo.GetParameters()
if pInfoArray <> null then
    for paramInfo in pInfoArray do
        // See if the ParamArray attribute is defined.
        let isDef = Attribute.IsDefined(paramInfo, typeof<ParamArrayAttribute>)

        if isDef then
            printfn $"\nThe ParamArray attribute is defined for \nparameter {paramInfo.Name} of method {mInfo.Name}."

        // See if ParamUsageAttribute is defined.
        // If so, display a message.
        let usageAttr =
            Attribute.GetCustomAttribute(paramInfo, typeof<ArgumentUsageAttribute>)
            :?> ArgumentUsageAttribute

        if usageAttr <> null then
            printfn $"\nThe ArgumentUsage attribute is defined for \nparameter {paramInfo.Name} of method {mInfo.Name}."
            printfn $"\n    The usage message for {paramInfo.Name} is:\n    \"{usageAttr.Message}\"."   
else
    printfn $"The parameters information could not be retrieved for method {mInfo.Name}."


// This example of Attribute.GetCustomAttribute(ParameterInfo, Type)
// generates the following output:
// The ArgumentUsage attribute is defined for
// parameter strArray of method TestMethod.
//
//     The usage message for strArray is:
//     "Must pass an array here.".
//
// The ParamArray attribute is defined for
// parameter strList of method TestMethod.
//
// The ArgumentUsage attribute is defined for
// parameter strList of method TestMethod.
//
//     The usage message for strList is:
//     "Can pass a parameter list or array here.".
' Example for the Attribute.GetCustomAttribute( ParameterInfo, Type ) method.
Imports System.Reflection

Namespace NDP_UE_VB

    ' Define a custom parameter attribute that takes a single message argument.
    <AttributeUsage(AttributeTargets.Parameter)>  _
    Public Class ArgumentUsageAttribute
        Inherits Attribute
           
        ' This is the attribute constructor.
        Public Sub New(UsageMsg As String)
            Me.usageMsg = UsageMsg
        End Sub

        ' usageMsg is storage for the attribute message.
        Protected usageMsg As String
           
        ' This is the Message property for the attribute.
        Public Property Message() As String
            Get
                Return usageMsg
            End Get
            Set
                usageMsg = value
            End Set
        End Property
    End Class

    Public Class BaseClass
       
        ' Assign an ArgumentUsage attribute to the strArray parameter.
        ' Assign a ParamArray attribute to strList using the ParamArray keyword.
        Public Overridable Sub TestMethod( _
            <ArgumentUsage("Must pass an array here.")> _
            strArray() As String, _
            ParamArray strList() As String)
        End Sub
    End Class

    Public Class DerivedClass
        Inherits BaseClass
           
        ' Assign an ArgumentUsage attribute to the strList parameter.
        ' Assign a ParamArray attribute to strList using the ParamArray keyword.
        Public Overrides Sub TestMethod( _
            strArray() As String, _
            <ArgumentUsage("Can pass a parameter list or array here.")> _
            ParamArray strList() As String)
        End Sub
    End Class

    Module CustomParamDemo
       
        Sub Main()
            Console.WriteLine( _
                "This example of Attribute.GetCustomAttribute" & _
                "( ParameterInfo, Type )" & vbCrLf & _
                "generates the following output.")
              
            ' Get the class type, and then get the MethodInfo object 
            ' for TestMethod to access its metadata.
            Dim clsType As Type = GetType(DerivedClass)
            Dim mInfo As MethodInfo = clsType.GetMethod("TestMethod")
              
            ' Iterate through the ParameterInfo array for the method parameters.
            Dim pInfoArray As ParameterInfo() = mInfo.GetParameters()
            If Not (pInfoArray Is Nothing) Then
                Dim paramInfo As ParameterInfo
                For Each paramInfo In  pInfoArray

                    ' See if the ParamArray attribute is defined.
                    Dim isDef As Boolean = _
                        Attribute.IsDefined(paramInfo, _
                            GetType(ParamArrayAttribute))

                    If isDef Then
                        Console.WriteLine( vbCrLf & _
                            "The ParamArray attribute is defined for " & _
                            vbCrLf & "parameter {0} of method {1}.", _
                            paramInfo.Name, mInfo.Name)
                    End If
                    
                    ' See if ParamUsageAttribute is defined.  
                    ' If so, display a message.
                    Dim usageAttr As ArgumentUsageAttribute = _
                        Attribute.GetCustomAttribute(paramInfo, _
                            GetType(ArgumentUsageAttribute))

                    If Not (usageAttr Is Nothing) Then
                        Console.WriteLine( vbCrLf & "The " & _
                            "ArgumentUsage attribute is defined for " & _
                            vbCrLf & "parameter {0} of method {1}.", _
                            paramInfo.Name, mInfo.Name)
                        Console.WriteLine( vbCrLf & _
                            "    The usage message for {0} is: " & _
                            vbCrLf & "    ""{1}"".", _
                            paramInfo.Name, usageAttr.Message)
                    End If
                Next paramInfo
            Else
                Console.WriteLine( _
                    "The parameters information could " & _
                    "not be retrieved for method {0}.", mInfo.Name)
            End If
        End Sub

    End Module ' DemoClass
End Namespace ' NDP_UE_VB

' This example of Attribute.GetCustomAttribute( ParameterInfo, Type )
' generates the following output.
' 
' The ArgumentUsage attribute is defined for
' parameter strArray of method TestMethod.
' 
'     The usage message for strArray is:
'     "Must pass an array here.".
' 
' The ParamArray attribute is defined for
' parameter strList of method TestMethod.
' 
' The ArgumentUsage attribute is defined for
' parameter strList of method TestMethod.
' 
'     The usage message for strList is:
'     "Can pass a parameter list or array here.".

Açıklamalar

Türetilmiş bir tür yöntemindeki bir parametreyi temsil ediyorsanız element , dönüş değeri geçersiz kılınan temel yöntemlerde aynı parametreye uygulanan devralınabilir özel öznitelikleri içerir.

Şunlara uygulanır