Attribute.IsDefaultAttribute 方法

当在派生类中重写时,指示此实例的值是否是派生类的默认值。

**命名空间:**System
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
Public Overridable Function IsDefaultAttribute As Boolean
用法
Dim instance As Attribute
Dim returnValue As Boolean

returnValue = instance.IsDefaultAttribute
public virtual bool IsDefaultAttribute ()
public:
virtual bool IsDefaultAttribute ()
public boolean IsDefaultAttribute ()
public function IsDefaultAttribute () : boolean

返回值

如果该实例是此类的默认属性,则为 true;否则,为 false

备注

此类的默认实现返回 false,并且必须在派生类中实现才能由此类使用。

此方法在派生类中的实现将此实例的值与标准默认值进行比较,然后返回一个布尔值,指示此实例的值是否等于标准值。标准值一般编码为实现中的常数,或者以编程方式存储在实现所使用的字段中。

示例

下面的代码示例演示 IsDefaultAttribute 的用法。

Imports System
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
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");
        }
    }
}
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" );
}
package ISelectionServiceExample; 

import System.*;
import System.Drawing.*;
import System.Collections.*;
import System.ComponentModel.*;
import System.ComponentModel.Design.*;
import System.Windows.Forms.*;

/*  This sample demonstrates using the ISelectionService
    interface to receive notification of selection change events.  
    The SelectionComponent control attempts to retrieve an instance 
    of the ISelectionService when it is sited. If it can, it attaches 
    event handlers for events provided by the service that display
    a message when a component is selected or deselected.

    To run this sample, add the SelectionComponent control to a Form and
    then select or deselect components in design mode to see the behavior 
    of the component change event handlers. 
 */
public class SelectionComponent extends System.Windows.Forms.UserControl
{    
    private System.Windows.Forms.TextBox tbox1;
    private ISelectionService selectionService;

    public SelectionComponent()
    {
        // Initialize control
        this.SuspendLayout();
        this.set_Name("SelectionComponent");
        this.set_Size(new System.Drawing.Size(608, 296));
        this.tbox1 = new System.Windows.Forms.TextBox();
        this.tbox1.set_Location(new System.Drawing.Point(24, 16));
        this.tbox1.set_Name("listBox1");
        this.tbox1.set_Multiline(true);
        this.tbox1.set_Size(new System.Drawing.Size(560, 251));
        this.tbox1.set_TabIndex(0);
        this.get_Controls().Add(this.tbox1);
        this.ResumeLayout();
    } //SelectionComponent

    /** @property
     */
    public ISite get_Site()
    {
        return super.get_Site();
    } //get_Site

    /** @property 
     */
    public void set_Site(ISite value)
    {
        // The ISelectionService is available in design mode 
        // only, and only after the component is sited.
        if (selectionService != null) {
            // Because the selection service has been 
            // previously obtained, the component may be in 
            // the process of being resited. 
            // Detatch the previous selection change event 
            // handlers in case the new selection
            // service is a new service instance belonging to 
            // another design mode service host.
            selectionService.remove_SelectionChanged(
                new EventHandler(OnSelectionChanged));
            selectionService.remove_SelectionChanging(
                new EventHandler(OnSelectionChanging));
        }
        // Establish the new site for the component.
        super.set_Site(value);
        if (super.get_Site() == null) {
            return;
        }
        // The selection service is not available outside of 
        // design mode. A call requesting the service 
        // using GetService while not in design mode will 
        // return null.
        selectionService = ((ISelectionService)(this.get_Site().
            GetService(ISelectionService.class.ToType())));

        // If an instance of the ISelectionService was obtained, 
        // attach event handlers for the selection 
        // changing and selection changed events.
        if (selectionService != null) {
            // Add an event handler for the SelectionChanging 
            // and SelectionChanged events.
            selectionService.add_SelectionChanging(
                new EventHandler(OnSelectionChanging));
            selectionService.add_SelectionChanged(
                new EventHandler(OnSelectionChanged));
        }
    } //set_Site

    private void OnSelectionChanged(Object sender, EventArgs args)
    {
        tbox1.AppendText(("The selected component was changed.  "
            + "Selected components:\r\n    " 
            + GetSelectedComponents() + "\r\n"));
    } //OnSelectionChanged

    private void OnSelectionChanging(Object sender, EventArgs args)
    {
        tbox1.AppendText(("The selected component is changing. "
            + "Selected components:\r\n    " 
            + GetSelectedComponents() + "\r\n"));
    } //OnSelectionChanging

    private String GetSelectedComponents()
    {
        String selectedString = "";
        Object components[] = new Object[((ICollection)(selectionService.
            GetSelectedComponents())).get_Count()];
        ((ICollection)(selectionService.GetSelectedComponents())).
            CopyTo(components, 0);
        for (int i = 0; i < components.length; i++) {
            if (i != 0) {
                selectedString += "&& ";
            }
            if (((IComponent)(selectionService.get_PrimarySelection())). 
                    Equals((IComponent)(components.get_Item(i)))) {
                selectedString += "PrimarySelection:";
            }
            selectedString += ((IComponent)(components.get_Item(i))).
                get_Site().get_Name() + " ";
        }
        return selectedString;
    } //GetSelectedComponents

    // Clean up any resources being used.
    protected void Dispose(boolean disposing)
    {
        // Detatch the event handlers for the selection service.
        if (selectionService != null) {
            selectionService.remove_SelectionChanging(
                new EventHandler(this.OnSelectionChanging));
            selectionService.remove_SelectionChanged(
                new EventHandler(this.OnSelectionChanged));
        }
        super.Dispose(disposing);
    } //Dispose
} //SelectionComponent
import System;
import System.Reflection;

package DefAttrJS {
    // 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.
    AttributeUsage(AttributeTargets.Method) public class AnimalTypeAttribute extends Attribute {
        // The constructor is called when the attribute is set.
        public function AnimalTypeAttribute(pet : Animal) {
            thePet = pet;
        }

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

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

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

        public function set Pet(value : Animal) {       
            thePet = value;
        }

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

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

    class DemoClass {
        static function Main() : void  {
            // Get the class type to access its metadata.
            var clsType : Type  = TestClass;
            // Get type information for the method.
            var mInfo : MethodInfo = clsType.GetMethod("Method1");
            // Get the AnimalType attribute for the method.
            var atAttr : AnimalTypeAttribute = 
                AnimalTypeAttribute(Attribute.GetCustomAttribute(mInfo, 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");
        }
    }
}

DefAttrJS.DemoClass.Main();

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

平台

Windows 98、Windows 2000 SP4、Windows Millennium Edition、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

请参见

参考

Attribute 类
Attribute 成员
System 命名空间