Partage via


Attribute.IsDefaultAttribute Méthode

Définition

En cas de substitution dans une classe dérivée, indique si la valeur de cette instance est la valeur par défaut pour la classe dérivée.

public:
 virtual bool IsDefaultAttribute();
public virtual bool IsDefaultAttribute ();
abstract member IsDefaultAttribute : unit -> bool
override this.IsDefaultAttribute : unit -> bool
Public Overridable Function IsDefaultAttribute () As Boolean

Retours

true si cette instance est l’attribut par défaut de la classe ; sinon, false.

Exemples

L’exemple de code suivant illustre l’utilisation de IsDefaultAttribute.

using namespace System;
using namespace System::Reflection;

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


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

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

   // Provide a default constructor and make Dog the default.
   AnimalTypeAttribute()
   {
      thePet = Animal::Dog;
   }

protected:

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

public:

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

   }

   // Override IsDefaultAttribute to return the correct response.
   virtual bool IsDefaultAttribute() override
   {
      return thePet == Animal::Dog;
   }
};

public ref class TestClass
{
public:

   // Use the default constructor.

   [AnimalType]
   void Method1(){}
};

int main()
{
   // Get the class type to access its metadata.
   Type^ clsType = TestClass::typeid;

   // Get type information for the method.
   MethodInfo^ mInfo = clsType->GetMethod( "Method1" );

   // Get the AnimalType attribute for the method.
   AnimalTypeAttribute^ atAttr = dynamic_cast<AnimalTypeAttribute^>(Attribute::GetCustomAttribute( mInfo, AnimalTypeAttribute::typeid ));

   // Check to see if the default attribute is applied.
   Console::WriteLine( "The attribute {0} for method {1} in class {2}", atAttr->Pet, mInfo->Name, clsType->Name );
   Console::WriteLine( "{0} the default for the AnimalType attribute.", atAttr->IsDefaultAttribute() ? (String^)"is" : "is not" );
}
using System;
using System.Reflection;

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

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

        // Provide a default constructor and make Dog the default.
        public AnimalTypeAttribute()
        {
            thePet = Animal.Dog;
        }

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

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

        // Override IsDefaultAttribute to return the correct response.
        public override bool IsDefaultAttribute()
        {
            if (thePet == Animal.Dog)
                return true;

            return false;
        }
    }

    public class TestClass
    {
        // Use the default constructor.
        [AnimalType]
        public void Method1()
        {}
    }

    class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(TestClass);
            // Get type information for the method.
            MethodInfo mInfo = clsType.GetMethod("Method1");
            // Get the AnimalType attribute for the method.
            AnimalTypeAttribute atAttr =
                (AnimalTypeAttribute)Attribute.GetCustomAttribute(mInfo,
                typeof(AnimalTypeAttribute));
            // Check to see if the default attribute is applied.
            Console.WriteLine("The attribute {0} for method {1} in class {2}",
                atAttr.Pet, mInfo.Name, clsType.Name);
            Console.WriteLine("{0} the default for the AnimalType attribute.",
                atAttr.IsDefaultAttribute() ? "is" : "is not");
        }
    }
}
open System

// An enumeration of animals. Start at 1 (0 = uninitialized).
type Animal =
    | Dog = 1
    | Cat = 2
    | Bird = 3

// A custom attribute to allow a target to have a pet.
type AnimalTypeAttribute(pet) =
    inherit Attribute()

    member val Pet = pet

    // Override IsDefaultAttribute to return the correct response.
    override _.IsDefaultAttribute() =
        pet = Animal.Dog

    // Provide a default constructor and make Dog the default.
    new() = AnimalTypeAttribute Animal.Dog

type TestClass() =
    // Use the default constructor.
    [<AnimalType>]
    member _.Method1() = ()

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

// Get type information for the method.
let mInfo = clsType.GetMethod "Method1"

// Get the AnimalType attribute for the method.
let atAttr = 
    Attribute.GetCustomAttribute(mInfo, typeof<AnimalTypeAttribute>) 
    :?> AnimalTypeAttribute

// Check to see if the default attribute is applied.
printf $"The attribute {atAttr.Pet} for method {mInfo.Name} in class {clsType.Name} "
printfn $"""{if atAttr.IsDefaultAttribute() then "is" else "is not"} the default for the AnimalType attribute."""

// Output:
//     The attribute Dog for method Method1 in class TestClass is the default for the AnimalType attribute.
Imports System.Reflection

Module DemoModule

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

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

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

        ' Provide a default constructor and make Dog the default.
        Public Sub New()
            thePet = Animal.Dog
        End Sub

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

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

        ' Override IsDefaultAttribute to return the correct response.
        Public Overrides Function IsDefaultAttribute() As Boolean
            If thePet = Animal.Dog Then
                Return True
            Else
                Return False
            End If
        End Function

    End Class

    Public Class TestClass
        ' Use the default constructor.
        <AnimalType()> _
        Public Sub Method1()
        End Sub

    End Class

    Sub Main()
        ' Get the class type to access its metadata.
        Dim clsType As Type = GetType(TestClass)
        ' Get type information for the method.
        Dim mInfo As MethodInfo = clsType.GetMethod("Method1")
        ' Get the AnimalType attribute for the method.
        Dim attr As Attribute = Attribute.GetCustomAttribute(mInfo, _
            GetType(AnimalTypeAttribute))
        If Not attr Is Nothing And TypeOf attr Is AnimalTypeAttribute Then
            ' Convert the attribute to the required type.
            Dim atAttr As AnimalTypeAttribute = _
                CType(attr, AnimalTypeAttribute)
            Dim strDef As String
            ' Check to see if the default attribute is applied.
            If atAttr.IsDefaultAttribute() Then
                strDef = "is"
            Else
                strDef = "is not"
            End If
            ' Display the result.
            Console.WriteLine("The attribute {0} for method {1} " & _
                    "in class {2}", atAttr.Pet.ToString(), mInfo.Name, _
                    clsType.Name)
            Console.WriteLine("{0} the default for the AnimalType " & _
                    "attribute.", strDef)
        End If
    End Sub
End Module

Remarques

L’implémentation par défaut de cette classe retourne falseet doit être implémentée dans la classe dérivée pour être utile à cette classe.

L’implémentation de cette méthode dans une classe dérivée compare la valeur de cette instance à une valeur par défaut standard, puis retourne une valeur booléenne qui indique si la valeur de cette instance est égale à la valeur standard. La valeur standard est généralement codée en tant que constante dans l’implémentation, ou stockée par programmation dans un champ utilisé par l’implémentation.

S’applique à