英語で読む

次の方法で共有


Attribute.Match(Object) メソッド

定義

派生クラス内でオーバーライドされたときに、指定したオブジェクトとこのインスタンスが等しいかどうかを示す値を返します。

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

パラメーター

obj
Object

Object のこのインスタンスと比較する Attribute

戻り値

Boolean

このインスタンスと obj が等しい場合は true。それ以外の場合は false

注釈

このメソッドは、1 つが Attribute 別のメソッドと等しいかどうかを判断します。 既定の実装は、2 つの属性が同じ型で、フィールド値が同じかどうかを決定する 、と同じです Equals

一般に、この Equals メソッドは、参照または値の等価性に関する標準テストを実行することを目的としています。 2 つの属性インスタンスが同じ型で同じ値を持つという条件以外の条件に基づいて、等価性のカスタム比較を実行する場合は、このメソッドをオーバーライド Match できます。 たとえば、次のシナリオでは、メソッドを Match オーバーライドして属性を比較できます。

  • 属性にはビット フィールドが含まれており、特定のビットが設定されている場合、2 つの属性インスタンスが等しいと見なされます。 たとえば、属性には、 NumericDisplay クライアントがサポートする数値形式 (バイナリ、8 進数、10 進数、16 進数など) を示すビット フィールドが含まれる場合があります。 オーバーライドされた Match メソッドは、2 つのインスタンスが同じ数値形式をサポートしている場合に等しいと見なす場合があります。

  • 属性には、同じ種類の情報を含む複数のフィールドが含まれているか、値を任意の順序で指定できる配列が含まれています。 たとえば、属性には Author 、作成者名の複数のフィールドが含まれる場合があります。 オーバーライドされた Match メソッドでは、各フィールドが対応するフィールドと等しいかどうかに関係なく、同じ作成者が存在する場合、2 つのインスタンスが等しいと見なされる場合があります。

次の例では、属性値の Match カスタム比較メソッドを作成する方法を示します。 内部的に作成者の AuthorsAttribute 名前を格納するオブジェクトを List<String> 定義する場合。 名前はリスト内の任意の順序で発生する可能性があるため、リスト内の位置に関係なく、作成者名を比較するメソッドがオーバーライド Match されます。 値の Equals 等価性のテストを実行するメソッドは、メソッドとは異なる結果を Match 返します。

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

適用対象

製品 バージョン
.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