Lire en anglais

Partager via


Attribute.Match(Object) Méthode

Définition

En cas de substitution dans une classe dérivée, retourne une valeur indiquant si cette instance équivaut à un objet spécifié.

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

Paramètres

obj
Object

Object à comparer à cette instance de Attribute.

Retours

true si cette instance équivaut à obj ; sinon, false.

Remarques

Cette méthode détermine si l’une Attribute est égale à une autre. Son implémentation par défaut est la même que Equals, ce qui détermine si deux attributs sont du même type et ont les mêmes valeurs de champ.

En général, la Equals méthode est destinée à effectuer un test standard pour la référence ou l’égalité des valeurs. Vous pouvez remplacer la Match méthode lorsque vous souhaitez effectuer une comparaison personnalisée pour l’égalité basée sur certains critères autres que le fait que deux instances d’attribut sont du même type et ont des valeurs identiques. Par exemple, vous pouvez remplacer la Match méthode pour comparer les attributs dans les scénarios suivants :

  • Un attribut comprend un champ bit, et vous considérez que deux instances d’attribut sont égales si un bit particulier est défini. Par exemple, un NumericDisplay attribut peut inclure un champ bit qui indique les formats numériques (tels que binaire, octal, décimal et hexadécimal) pris en charge par un client. La méthode remplacée Match peut considérer deux instances comme égales si elles prennent en charge le même format numérique.

  • Un attribut inclut plusieurs champs qui contiennent le même type d’informations, ou il contient un tableau dans lequel les valeurs peuvent être dans n’importe quel ordre. Par exemple, un Author attribut peut inclure plusieurs champs pour les noms d’auteur. La méthode remplacée Match peut considérer deux instances comme égales si elles ont les mêmes auteurs, que chaque champ soit ou non égal au champ correspondant.

 Exemple

L’exemple suivant illustre l’utilisation de pour créer une méthode de Match comparaison personnalisée pour les valeurs d’attribut. Si définit un AuthorsAttribute qui contient en interne un List<String> qui stocke les noms des auteurs. Étant donné que les noms peuvent se produire dans n’importe quel ordre dans la liste, il remplace la Match méthode permettant de comparer les noms d’auteurs, quelle que soit leur position dans la liste. Notez que la Equals méthode, qui effectue un test d’égalité de valeur, retourne des résultats différents de la Match méthode.

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

S’applique à

Produit Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.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, 4.8.1
.NET Standard 2.0, 2.1