Прочитать на английском

Поделиться через


Attribute.IsDefaultAttribute Метод

Определение

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

public virtual bool IsDefaultAttribute();

Возвращаемое значение

Значение true, если этот экземпляр является атрибутом по умолчанию для класса; в противном случае — значение false.

Примеры

В следующем примере кода показано использование IsDefaultAttribute.

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");
        }
    }
}

Комментарии

Реализация этого класса по умолчанию возвращает false, и должна быть реализована в производном классе, чтобы быть полезным для этого класса.

Реализация этого метода в производном классе сравнивает значение этого экземпляра со стандартным значением по умолчанию, а затем возвращает логическое значение, указывающее, равно ли значение этого экземпляра стандартному значению. Стандартное значение обычно кодируется как константа в реализации или хранится программным способом в поле, используемом реализацией.

Применяется к

Продукт Версии
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1