Attribute.Match(Object) Metoda

Definicja

W przypadku zastąpienia w klasie pochodnej zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi.

public:
 virtual bool Match(System::Object ^ obj);
public virtual bool Match (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

Parametry

obj
Object

Element Object do porównania z tym wystąpieniem klasy Attribute.

Zwraca

truejeśli to wystąpienie jest równe obj; w przeciwnym razie . false

Uwagi

Ta metoda określa, czy jedna Attribute jest równa innej. Jego domyślna implementacja jest taka sama jak Equals, która określa, czy dwa atrybuty są tego samego typu i mają te same wartości pól.

Ogólnie rzecz biorąc, Equals metoda jest przeznaczona do przeprowadzania standardowego testu dla równości odwołań lub wartości. Możesz zastąpić metodę Match , jeśli chcesz wykonać niestandardowe porównanie równości, które jest oparte na niektórych kryteriach innych niż dwa wystąpienia atrybutów są tego samego typu i mają identyczne wartości. Można na przykład zastąpić metodę Match , aby porównać atrybuty w następujących scenariuszach:

  • Atrybut zawiera pole bitowe i można rozważyć dwa wystąpienia atrybutów równe, jeśli określony bit jest ustawiony. Na przykład NumericDisplay atrybut może zawierać pole bitowe wskazujące formaty liczbowe (takie jak binarne, ósemkowe, dziesiętne i szesnastkowe) obsługiwane przez klienta. Metoda przesłonięć Match może rozważyć dwa wystąpienia równe, jeśli obsługują ten sam format liczbowy.

  • Atrybut zawiera wiele pól zawierających ten sam rodzaj informacji lub zawiera tablicę, w której wartości mogą znajdować się w dowolnej kolejności. Na przykład Author atrybut może zawierać wiele pól dla nazw autorów. Metoda przesłonięć Match może rozważyć dwa wystąpienia równe, jeśli mają tych samych autorów, niezależnie od tego, czy każde pole jest równe odpowiedniemu polu.

Przykład

Poniższy przykład ilustruje użycie Match metody do tworzenia niestandardowej metody porównania dla wartości atrybutów. Jeśli definiuje element AuthorsAttribute , który wewnętrznie zawiera List<String> nazwy autorów. Ponieważ nazwy mogą występować w dowolnej kolejności na liście, zastępuje Match metodę porównywania nazw autorów niezależnie od ich pozycji na liście. Zwróć uwagę na metodę Equals , która wykonuje test równości wartości, zwraca różne wyniki z Match metody .

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
open System

// A custom attribute to allow multiple authors per method.
[<AttributeUsage(AttributeTargets.Method); AllowNullLiteral>]
type AuthorsAttribute([<ParamArray>] names: string []) =
    inherit Attribute()

    member val Authors = ResizeArray names

    // Determine if the object is a match to this one.
    override this.Match(obj) =
        match obj with 
        | :? AuthorsAttribute as authors2 ->
            // Return true if obj and this instance are the same object reference.
            if Object.ReferenceEquals(this, authors2) then true
            // Return false if obj and this instance have different numbers of authors
            elif this.Authors.Count <> authors2.Authors.Count then false 
            else
                let authors1 = this.Authors |> set
                let authors2 = this.Authors |> set
                authors1 = authors2
        | _ ->
            // Return false if obj is null or not an AuthorsAttribute.
            false

    override this.ToString() =
        let retval = String.Join(", ", this.Authors)
        if retval.Trim().Length = 0 then 
            "<unknown>" 
        else 
            retval

// Add some authors to methods of a class.
type TestClass() =
    [<Authors("Leo Tolstoy", "John Milton")>]
    member _.Method1() = ()

    [<Authors "Anonymous">]
    member _.Method2() = ()

    [<Authors("Leo Tolstoy", "John Milton", "Nathaniel Hawthorne")>]
    member _.Method3() = ()

    [<Authors("John Milton", "Leo Tolstoy")>]
    member _.Method4() = ()

// Get the type for TestClass to access its metadata.
let clsType = typeof<TestClass>

// Iterate through each method of the class.

let mutable authors = null
for method in clsType.GetMethods() do
    // Check each method for the Authors attribute.
    let authAttr = 
        Attribute.GetCustomAttribute(method, typeof<AuthorsAttribute>)
        :?> AuthorsAttribute

    if authAttr <> null then
        // Display the authors.
        printfn $"{clsType.Name}.{method.Name} was authored by {authAttr}."

        // Select Method1's authors as the basis for comparison.
        if method.Name = "Method1" then
            authors <- authAttr
            printfn ""

        else
            // Compare first authors with the authors of this method.
            if authors.Match authAttr then
                printfn "TestClass.Method1 was also authored by the same team."

            // Perform an equality comparison of the two attributes.
            printfn $"""{authors} {if authors.Equals(authAttr) then "=" else "<>"} {authAttr}"""
            printfn ""

// 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

Dotyczy