Attribute.Match(Object) 方法

定義

在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。

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

參數

obj
Object

Object 的這個執行個體相互比較的 Attribute

傳回

如果這個執行個體等於 obj,則為 true,否則為 false

備註

這個方法會判斷其中一個是否等於另一個 Attribute 。 其預設實作與 相同 Equals ,可判斷兩個屬性是否屬於相同類型,而且具有相同的域值。

一般而言, Equals 方法的目的是要執行標準測試以取得參考或值相等。 當您想要針對相等執行自訂比較時,您可以覆寫 Match 方法,此比較是以兩個屬性實例屬於相同類型且具有相同值的一些準則為基礎。 例如,您可以覆寫 Match 方法來比較下列案例中的屬性:

  • 屬性包含位欄位,而且如果設定了特定位,您就會考慮兩個屬性實例相等。 例如, NumericDisplay 屬性可能包含一個位欄位,指出用戶端支援的數值格式 (,例如二進位、八進位、十六進位和十六進位) 。 如果兩個實例支援相同的數值格式,覆寫 Match 方法可能會考慮兩個實例相等。

  • 屬性包含多個包含相同資訊類型的欄位,或包含可依任何順序排列值的陣列。 例如, Author 屬性可能包含多個欄位以供作者名稱使用。 不論每個欄位是否等於對應的欄位,覆寫 Match 方法都可能會考慮兩個實例是否相等。

範例

下列範例說明 如何使用 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, 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