Attribute.Match(Object) Method

Definition

파생된 클래스에서 재정의할 경우,이 인스턴스가 지정된 된 개체와 같은지 여부를 나타내는 값을 반환 합니다.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

public:
 virtual bool Match(System::Object ^ obj);
public virtual bool Match (object obj);
abstract member Match : obj -> bool
override this.Match : obj -> bool
Public Overridable Function Match (obj As Object) As Boolean

Parameters

obj
Object

Object의 이 인스턴스와 비교할 Attribute입니다.An Object to compare with this instance of Attribute.

Returns

Boolean

이 인스턴스가 obj와 같으면 true이고, 그렇지 않으면 false입니다.true if this instance equals obj; otherwise, false.

Remarks

이 메서드는 한 Attribute 다른와 같은지 여부를 확인 합니다.This method determines if one Attribute equals another. 기본 구현은 Equals와 동일 합니다 .이는 두 특성이 동일한 형식이 고 동일한 필드 값을 갖는지 여부를 결정 합니다.Its default implementation is the same as Equals, which determines whether two attributes are of the same type and have the same field values.

일반적으로 Equals 메서드는 참조 또는 값 일치에 대 한 표준 테스트를 수행 하기 위한 것입니다.In general, the Equals method is intended to perform a standard test for reference or value equality. 두 특성 인스턴스가 동일한 형식이 고 동일한 값을 가지는 것 이외의 다른 조건을 기반으로 하는 같음에 대 한 사용자 지정 비교를 수행 하려는 경우 Match 메서드를 재정의할 수 있습니다.You can override the Match method when you want to perform a custom comparison for equality that is based on some criteria other than that two attribute instances are of the same type and have identical values. 예를 들어 다음과 같은 시나리오에서 Match 메서드를 재정의 하 여 특성을 비교할 수 있습니다.For example, you can override the Match method to compare attributes in the following scenarios:

  • 비트 필드를 포함 하는 특성 및 특성의 두 인스턴스가 같은 특정 비트가 설정 된 경우를 고려해 야 합니다.An attribute includes a bit field, and you consider two attribute instances equal if a particular bit is set. 예를 들어 NumericDisplay 특성에는 클라이언트에서 지 원하는 숫자 형식 (예: 이진, 8 진수, 10 진수 및 16 진수)을 나타내는 비트 필드가 포함 될 수 있습니다.For example, a NumericDisplay attribute might include a bit field that indicates what numeric formats (such as binary, octal, decimal, and hexadecimal) a client supports. 재정의 된 Match 메서드는 동일한 숫자 형식을 지 원하는 경우 두 개의 인스턴스를 동일한 것으로 간주할 수 있습니다.The overridden Match method might consider two instances equal if they support the same numeric format.

  • 같은 종류의 정보를 포함 하는 여러 필드를 포함 하는 특성 또는 값 순서에 관계 없이 사용할 수 있는 배열을 포함 합니다.An attribute includes multiple fields that contain the same kind of information, or it contains an array in which values can be in any order. 예를 들어 Author 특성은 author 이름에 대해 여러 필드를 포함할 수 있습니다.For example, an Author attribute might include multiple fields for author names. 재정의 된 Match 메서드는 각 필드가 해당 필드와 같은지 여부와 관계 없이 동일한 작성자가 있는 경우 두 개의 인스턴스를 동일한 것으로 간주할 수 있습니다.The overridden Match method might consider two instances equal if they have the same authors regardless of whether each field is equal to the corresponding field.

예제Example

다음 예에서는 Match를 사용 하 여 특성 값에 대 한 사용자 지정 비교 메서드를 만드는 방법을 보여 줍니다.The following example illustrates the use of Match to create a custom comparison method for attribute values. 가 작성자의 이름을 저장 하는 List<String>을 내부적으로 포함 하는 AuthorsAttribute를 정의 합니다.If defines an AuthorsAttribute that internally contains a List<String> that stores authors' names. 이름은 목록에서 순서에 관계 없이 나타날 수 있기 때문에 Match 메서드를 재정의 하 여 목록에서의 위치에 관계 없이 작성자 이름을 비교 합니다.Because the names can occur in any order in the list, it overrides the Match method to compare author names regardless of their position in the list. 참고 값이 같은지 테스트를 수행 하는 Equals 메서드는 Match 메서드와 다른 결과를 반환 합니다.Note the Equals method, which performs a test for value equality, returns different results from the Match method.

using System;
using System.Collections.Generic;
using System.Reflection;

// A custom attribute to allow multiple authors per method.
[AttributeUsage(AttributeTargets.Method)]
public class AuthorsAttribute : Attribute
{
   protected List<string> _authors;

    public AuthorsAttribute(params string[] names)
   {
      _authors = new List<string>(names);
    }

   public List<string> Authors
   {
       get { return _authors; }
   }

    // Determine if the object is a match to this one.
    public override bool Match(object obj)
   {
      // Return false if obj is null or not an AuthorsAttribute.
      AuthorsAttribute authors2 = obj as AuthorsAttribute;
      if (authors2 == null) return false;

        // Return true if obj and this instance are the same object reference.
      if (Object.ReferenceEquals(this, authors2))
         return true;

      // Return false if obj and this instance have different numbers of authors
      if (_authors.Count != authors2._authors.Count)
         return false;

      bool matches = false;
      foreach (var author in _authors)
      {
         for (int ctr = 0; ctr < authors2._authors.Count; ctr++)
         {
            if (author == authors2._authors[ctr])
            {
               matches = true;
               break;
            }
            if (ctr == authors2._authors.Count)
            {
               matches = false;
            }
         }
      }
      return matches;
   }

   public override string ToString()
   {
      string retval = "";
      for (int ctr = 0; ctr < _authors.Count; ctr++)
      {
         retval += $"{_authors[ctr]}{(ctr < _authors.Count - 1 ? ", " : String.Empty)}";
      }
      if (retval.Trim().Length == 0)
      {
         return "<unknown>";
      }
      return retval;
   }
}

// Add some authors to methods of a class.
public class TestClass {
    [Authors("Leo Tolstoy", "John Milton")]
    public void Method1()
    {}

    [Authors("Anonymous")]
    public void Method2()
    {}

    [Authors("Leo Tolstoy", "John Milton", "Nathaniel Hawthorne")]
    public void Method3()
    {}

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

class Example
{
    static void Main()
   {
        // Get the type for TestClass to access its metadata.
        Type clsType = typeof(TestClass);

        // Iterate through each method of the class.
      AuthorsAttribute authors = null;
        foreach(var method in clsType.GetMethods())
      {
            // Check each method for the Authors attribute.
            AuthorsAttribute authAttr = (AuthorsAttribute)  Attribute.GetCustomAttribute(method,
                                         typeof(AuthorsAttribute));
            if (authAttr != null)
         {
            // Display the authors.
                Console.WriteLine($"{clsType.Name}.{method.Name} was authored by {authAttr}.");

            // Select Method1's authors as the basis for comparison.
            if (method.Name == "Method1")
            {
                   authors = authAttr;
               Console.WriteLine();
               continue;
            }

            // Compare first authors with the authors of this method.
            if (authors.Match(authAttr))
            {
                    Console.WriteLine("TestClass.Method1 was also authored by the same team.");
            }

            // Perform an equality comparison of the two attributes.
            Console.WriteLine($"{authors} {(authors.Equals(authAttr) ? "=" : "<>")} {authAttr}");
            Console.WriteLine();
            }
        }
    }
}
// The example displays the following output:
//       TestClass.Method1 was authored by Leo Tolstoy, John Milton.
//
//       TestClass.Method2 was authored by Anonymous.
//       Leo Tolstoy, John Milton <> Anonymous
//
//       TestClass.Method3 was authored by Leo Tolstoy, John Milton, Nathaniel Hawthorne.
//       Leo Tolstoy, John Milton <> Leo Tolstoy, John Milton, Nathaniel Hawthorne
//
//       TestClass.Method4 was authored by John Milton, Leo Tolstoy.
//       TestClass.Method1 was also authored by the same team.
//       Leo Tolstoy, John Milton <> John Milton, Leo Tolstoy
Imports System.Collections.Generic
Imports System.Reflection
                                                               
' A custom attribute to allow multiple authors per method.
<AttributeUsage(AttributeTargets.Method)> _
Public Class AuthorsAttribute : Inherits Attribute 
   Protected _authors As List(Of String)

    Public Sub New(paramarray names As String()) 
      _authors = New List(Of string)(names)
    End Sub

   Public ReadOnly Property Authors As List(Of String) 
       Get 
         Return _authors
      End Get   
   End Property

    ' Determine if the object is a match to this one.
    Public Overrides Function Match(obj As Object) As Boolean 
      ' Return false if obj is null or not an AuthorsAttribute.
      Dim authors2 As AuthorsAttribute = DirectCast(obj, AuthorsAttribute)
      If authors2 Is Nothing Then Return False
      
        ' Return true if obj and this instance are the same object reference.
      If Object.ReferenceEquals(Me, authors2) Then Return True

      ' Return false if obj and this instance have different numbers of authors
      If _authors.Count <> authors2._authors.Count Then Return False
         
      Dim matches As Boolean = False
      For Each author in _authors 
         For ctr As Integer = 0 To authors2._authors.Count - 1
            If author = authors2._authors(ctr) Then
               matches = True
               Exit For
            End If
            If ctr = authors2._authors.Count Then matches = False
         Next
      Next
      Return matches
   End Function

   Public Overrides Function ToString() As String
      Dim retval As String = ""
      For ctr As Integer = 0 To _authors.Count -1
         retval += $"{_authors(ctr)}{If(ctr < _authors.Count - 1, ", ", String.Empty)}"
      Next
      If retval.Trim().Length = 0 Then Return "<unknown>"

      Return retval
   End Function
End Class

' Add some authors to methods of a class.
Public Class TestClass 
    <Authors("Leo Tolstoy", "John Milton")>
    Public sub Method1()
    End sub

    <Authors("Anonymous")>
    Public Sub Method2()
    End Sub

    <Authors("Leo Tolstoy", "John Milton", "Nathaniel Hawthorne")>
    Public Sub Method3()
    End Sub

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

Public Module Example 
    Public Sub Main() 
        ' Get the type for TestClass to access its metadata.
        Dim clsType As Type = GetType(TestClass)

        ' Iterate through each method of the class.
      Dim authors As AuthorsAttribute = Nothing
        For Each method In clsType.GetMethods() 
            ' Check each method for the Authors attribute.
            Dim authAttr As AuthorsAttribute = DirectCast(Attribute.GetCustomAttribute(method, 
                                         GetType(AuthorsAttribute)), AuthorsAttribute)
            If authAttr IsNot Nothing Then 
            ' Display the authors.
                Console.WriteLine($"{clsType.Name}.{method.Name} was authored by {authAttr}.")

            ' Select Method1's authors as the basis for comparison.
            If method.Name = "Method1" Then
                   authors = authAttr
               Console.WriteLine()
               Continue For
            End If
         
            ' Compare first authors with the authors of this method.
            If authors.Match(authAttr) Then
                    Console.WriteLine("TestClass.Method1 was also authored by the same team.")
            End If

            ' Perform an equality comparison of the two attributes.
            Console.WriteLine($"{authors} {If(authors.Equals(authAttr), "=", "<>")} {authAttr}")
            Console.WriteLine()
            End If
      Next
   End Sub
End Module
' The example displays the following output:
//       TestClass.Method1 was authored by Leo Tolstoy, John Milton.
//       
//       TestClass.Method2 was authored by Anonymous.
//       Leo Tolstoy, John Milton <> Anonymous
//       
//       TestClass.Method3 was authored by Leo Tolstoy, John Milton, Nathaniel Hawthorne.
//       Leo Tolstoy, John Milton <> Leo Tolstoy, John Milton, Nathaniel Hawthorne
//       
//       TestClass.Method4 was authored by John Milton, Leo Tolstoy.
//       TestClass.Method1 was also authored by the same team.
//       Leo Tolstoy, John Milton <> John Milton, Leo Tolstoy

Applies to