다음을 통해 공유


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 네임스페이스