다음을 통해 공유


Attribute.Match 메서드

파생 클래스에서 재정의된 경우 이 인스턴스가 지정된 개체와 같은지 여부를 나타내는 값을 반환합니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
Public Overridable Function Match ( _
    obj As Object _
) As Boolean
‘사용 방법
Dim instance As Attribute
Dim obj As Object
Dim returnValue As Boolean

returnValue = instance.Match(obj)
public virtual bool Match (
    Object obj
)
public:
virtual bool Match (
    Object^ obj
)
public boolean Match (
    Object obj
)
public function Match (
    obj : Object
) : boolean

매개 변수

반환 값

이 인스턴스가 obj와 같으면 true이고, 그렇지 않으면 false입니다.

설명

이 메서드는 한 Attribute가 다른 특성과 같은지 확인합니다. 기본 구현은 Equals와 같이 값과 참조를 비교합니다. 이 메서드를 재정의하여 그 자체로 의미가 있는 구성 요소를 구성하는 플래그나 비트 필드와 같은 특성 값을 지원하도록 구현합니다.

예를 들어, 한 특성 값이 플래그의 비트 필드로 나누어진 이진 필드라고 가정하면 이 특성의 두 인스턴스는 다른 플래그가 달라도 일반적으로 설정된 하나의 플래그를 가지게 됩니다. Equals 메서드를 사용하면 두 인스턴스가 같은 플래그를 가진다고 간주하지 않지만 Match 메서드는 그렇게 할 수 있습니다.

예제

다음 코드 예제에서는 Attribute 컨텍스트에서 Match를 사용하는 방법을 보여 줍니다.

Imports System
Imports System.Reflection

Module DemoModule

    ' A custom attribute to allow 2 authors per method.
    <AttributeUsage(AttributeTargets.Method)> _
    Public Class AuthorsAttribute
        Inherits Attribute

        Public Sub New(ByVal name1 As String, ByVal name2 As String)
            myAuthorName1 = name1
            myAuthorName2 = name2
        End Sub

        Protected myAuthorName1 As String
        Protected myAuthorName2 As String

        Public Property AuthorName1() As String
            Get
                Return myAuthorName1
            End Get
            Set(ByVal Value As String)
                myAuthorName1 = AuthorName1
            End Set
        End Property

        Public Property AuthorName2() As String
            Get
                Return myAuthorName2
            End Get
            Set(ByVal Value As String)
                myAuthorName2 = AuthorName2
            End Set
        End Property

        ' Use the hash code of the string objects and xor them together.
        Public Overrides Function GetHashCode() As Integer
            Return myAuthorName1.GetHashCode() Xor myAuthorName2.GetHashCode()
        End Function

        ' Determine if the object is a match to this one.
        Public Overrides Function Match(ByVal obj As Object) As Boolean
            ' Obviously a match.
            If obj Is Me Then
                Return True
            End If

            ' Obviously we're not nothing, so no.
            If obj Is Nothing Then
                Return False
            End If

            If TypeOf obj Is AuthorsAttribute Then
                ' Combine the hash codes and see if they're unchanged.
                Dim authObj As AuthorsAttribute = CType(obj, AuthorsAttribute)
                Dim firstHash As Integer = authObj.GetHashCode() And GetHashCode()
                If firstHash = GetHashCode() Then
                    Return True
                Else
                    Return False
                End If
            Else
                Return False
            End If
        End Function

    End Class

    ' Add some authors to methods of a class.
    Public Class TestClass1
        <Authors("William Shakespeare", "Herman Melville")> _
        Public Sub Method1()
        End Sub

        <Authors("Leo Tolstoy", "John Milton")> _
        Public Sub Method2()
        End Sub
    End Class

    ' Add authors to a second class's methods.
    Public Class TestClass2
        <Authors("William Shakespeare", "Herman Melville")> _
        Public Sub Method1()
        End Sub

        <Authors("Leo Tolstoy", "John Milton")> _
        Public Sub Method2()
        End Sub

        <Authors("Francis Bacon", "Miguel Cervantes")> _
        Public Sub Method3()
        End Sub
    End Class

    Sub Main()
        ' Get the type for both classes to access their metadata.
        Dim clsType1 As Type = GetType(TestClass1)
        Dim clsType2 As Type = GetType(TestClass2)

        Dim mInfo1 As MethodInfo
        ' Iterate through each method of the first class.
        For Each mInfo1 In clsType1.GetMethods()
            ' Check each method for the Authors attribute.
            Dim attr1 As Attribute = Attribute.GetCustomAttribute(mInfo1, _
                GetType(AuthorsAttribute))
            If Not attr1 Is Nothing And TypeOf attr1 Is AuthorsAttribute Then
                Dim authAttr1 As AuthorsAttribute = _
                    CType(attr1, AuthorsAttribute)
                ' Display the authors.
                Console.WriteLine("Method {0} was authored by {1} and {2}.", _
                                mInfo1.Name, authAttr1.AuthorName1, _
                                authAttr1.AuthorName2)
                Dim mInfo2 As MethodInfo
                ' Iterate through each method of the second class.
                For Each mInfo2 In clsType2.GetMethods()
                    ' Check each method for the Authors attribute.
                    Dim attr2 As Attribute = Attribute.GetCustomAttribute( _
                        mInfo2, GetType(AuthorsAttribute))
                    If Not attr2 Is Nothing And _
                        TypeOf attr2 Is AuthorsAttribute Then
                        Dim authAttr2 As AuthorsAttribute = _
                            CType(attr2, AuthorsAttribute)
                        ' Compare with the authors in the first class.
                        If authAttr2.Match(authAttr1) = True Then
                            Console.WriteLine("Method {0} in class {1} was " + _
                                        "also authored by the same team.", _
                                        mInfo2.Name, clsType2.Name)
                        End If
                    End If
                Next
                Console.WriteLine("")
            End If
        Next
    End Sub
End Module

' Output:
' Method Method1 was authored by William Shakespeare and Herman Melville.
' Method Method1 in class TestClass2 was also authored by the same team.
' 
' Method Method2 was authored by Leo Tolstoy and John Milton.
' Method Method2 in class TestClass2 was also authored by the same team.
using System;
using System.Reflection;

namespace MatchCS {
    // A custom attribute to allow 2 authors per method.
    public class AuthorsAttribute : Attribute {
        public AuthorsAttribute(string name1, string name2) {
            authorName1 = name1;
            authorName2 = name2;
        }

        protected string authorName1;
        protected string authorName2;
    
        public string AuthorName1 {
            get { return authorName1; }
            set { authorName1 = AuthorName1; }
        }

        public string AuthorName2 {
            get { return authorName2; }
            set { authorName2 = AuthorName2; }
        }

        // Use the hash code of the string objects and xor them together.
        public override int GetHashCode() {
            return authorName1.GetHashCode() ^ authorName2.GetHashCode();
        }

        // Determine if the object is a match to this one.
        public override bool Match(object obj) {
            // Obviously a match.
            if (obj == this)
                return true;

            // Obviously we're not null, so no.
            if (obj == null)
                return false;

            if (obj is AuthorsAttribute)
                // Combine the hash codes and see if they're unchanged.
                return (((AuthorsAttribute)obj).GetHashCode() & GetHashCode())
                    == GetHashCode();
            else
                return false;
        }
    }

    // Add some authors to methods of a class.
    public class TestClass1 {
        [Authors("William Shakespeare", "Herman Melville")]
        public void Method1()
        {}

        [Authors("Leo Tolstoy", "John Milton")]
        public void Method2()
        {}
    }

    // Add authors to a second class's methods.
    public class TestClass2 {
        [Authors("William Shakespeare", "Herman Melville")]
        public void Method1()
        {}

        [Authors("Leo Tolstoy", "John Milton")]
        public void Method2()
        {}

        [Authors("William Shakespeare", "John Milton")]
        public void Method3()
        {}
    }

    class DemoClass {
        static void Main(string[] args) {
            // Get the type for both classes to access their metadata.
            Type clsType1 = typeof(TestClass1);
            Type clsType2 = typeof(TestClass2);

            // Iterate through each method of the first class.
            foreach(MethodInfo mInfo1 in clsType1.GetMethods()) {
                // Check each method for the Authors attribute.
                AuthorsAttribute authAttr1 = (AuthorsAttribute)
                    Attribute.GetCustomAttribute(mInfo1, 
                    typeof(AuthorsAttribute));
                if (authAttr1 != null) {
                    // Display the authors.
                    Console.WriteLine("Method {0} was authored by {1} " +
                                        "and {2}.", mInfo1.Name, 
                                        authAttr1.AuthorName1, 
                                        authAttr1.AuthorName2);
                    // Iterate through each method of the second class.
                    foreach(MethodInfo mInfo2 in clsType2.GetMethods()) {
                        // Check each method for the Authors attribute.
                        AuthorsAttribute authAttr2 = (AuthorsAttribute)
                            Attribute.GetCustomAttribute(mInfo2, 
                            typeof(AuthorsAttribute));
                        // Compare with the authors in the first class.
                        if (authAttr2 != null && authAttr2.Match(authAttr1))
                            Console.WriteLine("Method {0} in class {1} " +
                                "was authored by the same team.",
                                mInfo2.Name, clsType2.Name);
                    }
                    Console.WriteLine("");
                }
            }
        }
    }
}

/*
 * Output:
 * Method Method1 was authored by William Shakespeare and Herman Melville.
 * Method Method1 in class TestClass2 was authored by the same team.
 * Method Method2 was authored by Leo Tolstoy and John Milton.
 * Method Method2 in class TestClass2 was authored by the same team.
 */
using namespace System;
using namespace System::Reflection;

// A custom attribute to allow 2 authors per method.
public ref class AuthorsAttribute: public Attribute
{
public:
   AuthorsAttribute( String^ name1, String^ name2 )
   {
      authorName1 = name1;
      authorName2 = name2;
   }

protected:
   String^ authorName1;
   String^ authorName2;

public:

   property String^ AuthorName1 
   {
      String^ get()
      {
         return authorName1;
      }

      void set( String^ value )
      {
         authorName1 = value;
      }
   }

   property String^ AuthorName2 
   {
      String^ get()
      {
         return authorName2;
      }

      void set( String^ value )
      {
         authorName2 = value;
      }
   }

   // Use the hash code of the string objects and xor them together.
   virtual int GetHashCode() override
   {
      return authorName1->GetHashCode() ^ authorName2->GetHashCode();
   }

   // Determine if the object is a match to this one.
   virtual bool Match( Object^ obj ) override
   {
      // Obviously a match.
      if ( obj == this )
            return true;

      // Obviously we're not null, so no.
      if ( obj == nullptr )
            return false;

      if ( dynamic_cast<AuthorsAttribute^>(obj) )

      // Combine the hash codes and see if they're unchanged.
      return (dynamic_cast<AuthorsAttribute^>(obj)->GetHashCode() & GetHashCode()) == GetHashCode();
      else
            return false;
   }
};


// Add some authors to methods of a class.
public ref class TestClass1
{
public:

   [Authors("William Shakespeare","Herman Melville")]
   void Method1(){}


   [Authors("Leo Tolstoy","John Milton")]
   void Method2(){}

};


// Add authors to a second class's methods.
public ref class TestClass2
{
public:

   [Authors("William Shakespeare","Herman Melville")]
   void Method1(){}


   [Authors("Leo Tolstoy","John Milton")]
   void Method2(){}


   [Authors("William Shakespeare","John Milton")]
   void Method3(){}

};

int main()
{
   // Get the type for both classes to access their metadata.
   Type^ clsType1 = TestClass1::typeid;
   Type^ clsType2 = TestClass2::typeid;

   // Iterate through each method of the first class.
   System::Collections::IEnumerator^ myEnum = clsType1->GetMethods()->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      MethodInfo^ mInfo1 = safe_cast<MethodInfo^>(myEnum->Current);

      // Check each method for the Authors attribute.
      AuthorsAttribute^ authAttr1 = dynamic_cast<AuthorsAttribute^>(Attribute::GetCustomAttribute( mInfo1, AuthorsAttribute::typeid ));
      if ( authAttr1 != nullptr )
      {
         // Display the authors.
         Console::WriteLine( "Method {0} was authored by {1} and {2}.", mInfo1->Name, authAttr1->AuthorName1, authAttr1->AuthorName2 );

         // Iterate through each method of the second class.
         System::Collections::IEnumerator^ myEnum1 = clsType2->GetMethods()->GetEnumerator();
         while ( myEnum1->MoveNext() )
         {
            MethodInfo^ mInfo2 = safe_cast<MethodInfo^>(myEnum1->Current);

            // Check each method for the Authors attribute.
            AuthorsAttribute^ authAttr2 = dynamic_cast<AuthorsAttribute^>(Attribute::GetCustomAttribute( mInfo2, AuthorsAttribute::typeid ));

            // Compare with the authors in the first class.
            if ( authAttr2 != nullptr && authAttr2->Match(authAttr1) )
                        Console::WriteLine( "Method {0} in class {1} was authored by the same team.", mInfo2->Name, clsType2->Name );
         }
         Console::WriteLine();
      }
   }
}

/*
 * Output:
 * Method Method1 was authored by William Shakespeare and Herman Melville.
 * Method Method1 in class TestClass2 was authored by the same team.
 * Method Method2 was authored by Leo Tolstoy and John Milton.
 * Method Method2 in class TestClass2 was authored by the same team.
 */
package MatchJSL;

import System.*;
import System.Reflection.*;

// A custom attribute to allow 2 authors per method.
/** @attribute AttributeUsage(AttributeTargets.Method, AllowMultiple = true)
 */
public class AuthorsAttribute extends Attribute
{
    public AuthorsAttribute(String name1, String name2)
    {
        authorName1 = name1;
        authorName2 = name2;
    } //AuthorsAttribute

    protected String authorName1;
    protected String authorName2;

    /** @property 
     */
    public String get_AuthorName1()
    {
        return authorName1;
    } //get_AuthorName1

    /** @property 
     */
    public void set_AuthorName1(String value)
    {
        authorName1 = value;
    } //set_AuthorName1

    /** @property 
     */
    public String get_AuthorName2()
    {
        return authorName2;
    } //get_AuthorName2

    /** @property 
     */
    public void set_AuthorName2(String value)
    {
        authorName2 = value;
    } //set_AuthorName2

    // Use the hash code of the string objects and xor them together.
    public int GetHashCode()
    {
        return authorName1.GetHashCode() ^ authorName2.GetHashCode();
    } //GetHashCode

    // Determine if the object is a match to this one.
    public boolean Match(Object obj)
    {
        // Obviously a match.
        if (obj.Equals(this)) {
            return true;
        }
        // Obviously we're not null, so no.
        if (obj == null) {
            return false;
        }

        if (obj instanceof AuthorsAttribute) {
            // Combine the hash codes and see if they're unchanged.
            return (((AuthorsAttribute)obj).GetHashCode() & GetHashCode())
                == GetHashCode();
        }
        else {
            return false;
        }
    } //Match
} //AuthorsAttribute

// Add some authors to methods of a class.
public class TestClass1
{
    /** @attribute Authors("William Shakespeare", "Herman Melville")
     */
    public void Method1()
    {
    } //Method1

    /** @attribute Authors("Leo Tolstoy", "John Milton")
     */
    public void Method2()
    {
    } //Method2
} //TestClass1

// Add authors to a second class's methods.
public class TestClass2
{
    /** @attribute Authors("William Shakespeare", "Herman Melville")
     */
    public void Method1()
    {
    } //Method1

    /** @attribute Authors("Leo Tolstoy", "John Milton")
     */
    public void Method2()
    {
    } //Method2

    /** @attribute Authors("William Shakespeare", "John Milton")
     */
    public void Method3()
    {
    } //Method3
} //TestClass2

class DemoClass
{
    public static void main(String[] args)
    {
        // Get the type for both classes to access their metadata.
        Type clsType1 = TestClass1.class.ToType();
        Type clsType2 = TestClass2.class.ToType();

        // Iterate through each method of the first class.
        for (int iCtr1 = 0; iCtr1 < clsType1.GetMethods().get_Length(); 
            iCtr1++) {
            MethodInfo mInfo1 = 
                (MethodInfo)clsType1.GetMethods().get_Item(iCtr1);

            // Check each method for the Authors attribute.
            AuthorsAttribute authAttr1 = 
                (AuthorsAttribute)Attribute.GetCustomAttribute(mInfo1, 
                AuthorsAttribute.class.ToType());
            if (authAttr1 != null) {
                // Display the authors.
                Console.WriteLine("Method {0} was authored by {1} " 
                    + "and {2}.", mInfo1.get_Name(), 
                    authAttr1.get_AuthorName1(), authAttr1.get_AuthorName2());

                // Iterate through each method of the second class.
                for (int iCtr2 = 0; iCtr2 < clsType1.GetMethods().get_Length(); 
                    iCtr2++) {
                    MethodInfo mInfo2 = (MethodInfo)clsType1.GetMethods().
                        get_Item(iCtr2);

                    // Check each method for the Authors attribute.
                    AuthorsAttribute authAttr2 = (AuthorsAttribute)Attribute.
                        GetCustomAttribute(mInfo2, 
                        AuthorsAttribute.class.ToType());

                    // Compare with the authors in the first class.
                    if (authAttr2 != null && authAttr2.Match(authAttr1)) {
                        Console.WriteLine("Method {0} in class {1} " 
                            + "was authored by the same team.", 
                            mInfo2.get_Name(), clsType2.get_Name());
                    }
                }
                Console.WriteLine("");
            }
        }
    } //main
} //DemoClass

/*
 * Output:
 * Method Method1 was authored by William Shakespeare and Herman Melville.
 * Method Method1 in class TestClass2 was authored by the same team.
 * Method Method2 was authored by Leo Tolstoy and John Milton.
 * Method Method2 in class TestClass2 was authored by the same team.
 */
import System;
import System.Reflection;

package MatchJS {
    // A custom attribute to allow 2 authors per method.
    AttributeUsage(AttributeTargets.Method) public class AuthorsAttribute extends Attribute {
        public function AuthorsAttribute(name1 : String, name2 : String) {
            authorName1 = name1;
            authorName2 = name2;
        }

        protected var authorName1 : String;
        protected var authorName2 : String ;

        public function get AuthorName1() : String {
            return authorName1;
    }
        public function set AuthorName1( value: String ) {
            authorName1 = value;
        }

        public function get AuthorName2() : String {
            return authorName2;
        }
        
        public function set AuthorName2(value : String){
            authorName2 = AuthorName2;
        }

        // Use the hash code of the string objects and xor them together.
        public override function GetHashCode() : int {
            return authorName1.GetHashCode() ^ authorName2.GetHashCode();
        }

        // Determine if the object is a match to this one.
        public override function Match(obj) : boolean {
            // Obviously a match.
            if (obj == this)
                return true;
            // Obviously we're not null, so no.
            if (obj == null)
                return false;

            if (obj instanceof AuthorsAttribute)
                // Combine the hash codes and see if they're unchanged.
                return (AuthorsAttribute(obj).GetHashCode() & GetHashCode())
                            == GetHashCode();
            else
                return false;
        }
    }

    // Add some authors to methods of a class.
    public class TestClass1 {
        Authors("William Shakespeare", "Herman Melville")
        public function Method1() : void 
        {}

        Authors("Leo Tolstoy", "John Milton")
        public function Method2() : void 
        {}
    }

    // Add authors to a second class's methods.
    public class TestClass2 {
        Authors("William Shakespeare", "Herman Melville")
        public function Method1() : void 
        {}

        Authors("Leo Tolstoy", "John Milton")
        public function Method2() : void
        {}

        Authors("William Shakespeare", "John Milton")
        public function Method3() : void 
        {}
    }

    class DemoClass {
        static function Main() : void {
            // Get the type for both classes to access their metadata.
            var clsType1 : Type = TestClass1;
            var clsType2 : Type = TestClass2;

            // Iterate through each method of the first class.
            var methods1 : MethodInfo[] = clsType1.GetMethods();
            for(var i : int in methods1) {
                var mInfo1 : MethodInfo = methods1[i];
                // Check each method for the Authors attribute.
                var authAttr1 : AuthorsAttribute = AuthorsAttribute(
                    Attribute.GetCustomAttribute(mInfo1, AuthorsAttribute));
                if (authAttr1 != null) {
                // Display the authors.
                Console.WriteLine("Method {0} was authored by {1} " +
                                    "and {2}.", mInfo1.Name, 
                                    authAttr1.AuthorName1, 
                                    authAttr1.AuthorName2);
                // Iterate through each method of the second class.
                var methods2 : MethodInfo[] = clsType2.GetMethods()
                for( var j : int in methods2) {
                        var mInfo2 : MethodInfo = methods2[j];
                        // Check each method for the Authors attribute.
                        var authAttr2 : AuthorsAttribute = AuthorsAttribute(
                            Attribute.GetCustomAttribute(mInfo2, 
                            AuthorsAttribute));
                        // Compare with the authors in the first class.
                        if (authAttr2 != null && authAttr2.Match(authAttr1))
                            Console.WriteLine("Method {0} in class {1} " +
                                "was authored by the same team.",
                                mInfo2.Name, clsType2.Name);
                }
                Console.WriteLine("");
                }
            }
        }
    }
}

MatchJS.DemoClass.Main();

/*
 * Output:
 * Method Method1 was authored by William Shakespeare and Herman Melville.
 * Method Method1 in class TestClass2 was authored by the same team.
 * Method Method2 was authored by Leo Tolstoy and John Milton.
 * Method Method2 in class TestClass2 was authored by the same team.
 */

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, 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에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Attribute 클래스
Attribute 멤버
System 네임스페이스