Leer en inglés

Compartir a través de


Attribute.Match(Object) Método

Definición

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.

C#
public virtual bool Match (object? obj);
C#
public virtual bool Match (object obj);

Parámetros

obj
Object

Object que se va a comparar con esta instancia de Attribute.

Devoluciones

Boolean

Es true si esta instancia es igual a obj; en caso contrario, es false.

Comentarios

Este método determina si uno Attribute es igual a otro. Su implementación predeterminada es la misma Equalsque , que determina si dos atributos son del mismo tipo y tienen los mismos valores de campo.

En general, el Equals método está pensado para realizar una prueba estándar para la igualdad de referencia o valor. Puede invalidar el Match método cuando desee realizar una comparación personalizada para la igualdad basada en algunos criterios distintos de que dos instancias de atributo tengan el mismo tipo y tengan valores idénticos. Por ejemplo, puede invalidar el Match método para comparar atributos en los escenarios siguientes:

  • Un atributo incluye un campo de bits y se consideran dos instancias de atributo iguales si se establece un bit determinado. Por ejemplo, un NumericDisplay atributo podría incluir un campo de bits que indica qué formatos numéricos (como binario, octal, decimal y hexadecimal) admite un cliente. El método invalidado Match podría considerar dos instancias iguales si admiten el mismo formato numérico.

  • Un atributo incluye varios campos que contienen el mismo tipo de información o contiene una matriz en la que los valores pueden estar en cualquier orden. Por ejemplo, un Author atributo podría incluir varios campos para los nombres de autor. El método invalidado Match puede considerar dos instancias iguales si tienen los mismos autores, independientemente de si cada campo es igual al campo correspondiente.

Ejemplo

En el ejemplo siguiente se muestra el uso de para crear un método de comparación personalizado para los valores de Match atributo. Si define un AuthorsAttribute objeto que contiene internamente un List<String> objeto que almacena los nombres de los autores. Dado que los nombres pueden producirse en cualquier orden de la lista, invalida el Match método para comparar nombres de autor independientemente de su posición en la lista. Observe el Equals método , que realiza una prueba para la igualdad de valores, devuelve resultados diferentes del Match método .

C#
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

Se aplica a

Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1