Attribute.Equals(Object) 方法

定義

傳回值,這個值指出此執行個體是否與指定的物件相等。Returns a value that indicates whether this instance is equal to a specified object.

public:
 override bool Equals(System::Object ^ obj);
public override bool Equals (object obj);
override this.Equals : obj -> bool
Public Overrides Function Equals (obj As Object) As Boolean

參數

obj
Object

要與這個執行個體或 null 相比較的 ObjectAn Object to compare with this instance or null.

傳回

如果 obj 和這個執行個體是相同的類型並擁有完全相同的欄位值,則為 true;否則為 falsetrue if obj and this instance are of the same type and have identical field values; otherwise, false.

範例

下列範例會定義兩個自訂參數 Attribute 類別,然後為每個類別建立數個物件,並使用 Equals 方法進行比較。The following example defines two custom parameter Attribute classes, then creates several objects of each class and uses the Equals method to compare them.


using namespace System;
using namespace System::Reflection;

 // Define a custom parameter attribute that takes a single message argument.

[AttributeUsage(AttributeTargets::Parameter)]
public ref class ArgumentUsageAttribute: public Attribute
{
    protected:
       // usageMsg is storage for the attribute message.
       String^ usageMsg;

    public:
       // This is the attribute constructor.
       ArgumentUsageAttribute( String^ UsageMsg )
       {
          this->usageMsg = UsageMsg;
       }


       // Override ToString() to append the message to what the base generates.
       virtual String^ ToString() override
       {
          return String::Concat( Attribute::ToString(), ":", usageMsg );
       }
} ;


 // Define a custom parameter attribute that generates a GUID for each instance.
[AttributeUsage(AttributeTargets::Parameter)]
public ref class ArgumentIDAttribute : Attribute
{
    protected:
        // instanceGUID is storage for the generated GUID.
        Guid instanceGUID;

    public:
        // This is the attribute constructor, which generates the GUID.
        ArgumentIDAttribute()
        {
           this->instanceGUID = Guid::NewGuid();
        }

        // Override ToString() to append the GUID to what the base generates.
        virtual String^ ToString() override
        {
           return String::Concat( Attribute::ToString(), ".", instanceGUID.ToString() );
        }
};

public ref class TestClass
{
   public:
      // Assign an ArgumentID attribute to each parameter.
      // Assign an ArgumentUsage attribute to each parameter.
      void TestMethod( [ArgumentID][ArgumentUsage("Must pass an array here.")]array<String^>^strArray, 
                       [ArgumentID][ArgumentUsage("Can pass param list or array here.")]array<String^>^strList ){}
};

int main()
{
      // Get the class type, and then get the MethodInfo object 
      // for TestMethod to access its metadata.
      Type^ clsType = TestClass::typeid;
      MethodInfo^ mInfo = clsType->GetMethod( "TestMethod" );

      // There will be two elements in pInfoArray, one for each parameter.
      array<ParameterInfo^>^pInfoArray = mInfo->GetParameters();
      if  (pInfoArray != nullptr)
      {
         // Create an instance of the argument usage attribute on strArray.
         ArgumentUsageAttribute^ arrayUsageAttr1 = static_cast<ArgumentUsageAttribute^>(Attribute::GetCustomAttribute( pInfoArray[ 0 ], ArgumentUsageAttribute::typeid ));

         // Create another instance of the argument usage attribute on strArray.
         ArgumentUsageAttribute^ arrayUsageAttr2 = static_cast<ArgumentUsageAttribute^>(Attribute::GetCustomAttribute( pInfoArray[ 0 ], ArgumentUsageAttribute::typeid ));

         // Create an instance of the argument usage attribute on strList.
         ArgumentUsageAttribute^ listUsageAttr = static_cast<ArgumentUsageAttribute^>(Attribute::GetCustomAttribute( pInfoArray[ 1 ], ArgumentUsageAttribute::typeid ));

         // Create an instance of the argument ID attribute on strArray.
         ArgumentIDAttribute^ arrayIDAttr1 = static_cast<ArgumentIDAttribute^>(Attribute::GetCustomAttribute( pInfoArray[ 0 ], ArgumentIDAttribute::typeid ));

         // Create another instance of the argument ID attribute on strArray.
         ArgumentIDAttribute^ arrayIDAttr2 = static_cast<ArgumentIDAttribute^>(Attribute::GetCustomAttribute( pInfoArray[ 0 ], ArgumentIDAttribute::typeid ));

         // Create an instance of the argument ID attribute on strList.
         ArgumentIDAttribute^ listIDAttr = static_cast<ArgumentIDAttribute^>(Attribute::GetCustomAttribute( pInfoArray[ 1 ], ArgumentIDAttribute::typeid ));

         // Compare various pairs of attributes for equality.
         Console::WriteLine( "\nCompare a usage attribute instance to "
         "another instance of the same attribute:" );
         Console::WriteLine( "   \"{0}\" == \n   \"{1}\" ? {2}", arrayUsageAttr1->ToString(), arrayUsageAttr2->ToString(), arrayUsageAttr1->Equals( arrayUsageAttr2 ) );
         Console::WriteLine( "\nCompare a usage attribute to another usage attribute:" );
         Console::WriteLine( "   \"{0}\" == \n   \"{1}\" ? {2}", arrayUsageAttr1->ToString(), listUsageAttr->ToString(), arrayUsageAttr1->Equals( listUsageAttr ) );
         Console::WriteLine( "\nCompare an ID attribute instance to "
         "another instance of the same attribute:" );
         Console::WriteLine( "   \"{0}\" == \n   \"{1}\" ? {2}", arrayIDAttr1->ToString(), arrayIDAttr2->ToString(), arrayIDAttr1->Equals( arrayIDAttr2 ) );
         Console::WriteLine( "\nCompare an ID attribute to another ID attribute:" );
         Console::WriteLine( "   \"{0}\" == \n   \"{1}\" ? {2}", arrayIDAttr1->ToString(), listIDAttr->ToString(), arrayIDAttr1->Equals( listIDAttr ) );
      }
      else
      {
            Console::WriteLine( "The parameters information could not be retrieved for method {0}.", mInfo->Name );
      }
}
/*
The example displays the following output:
      Compare a usage attribute instance to another instance of the same attribute:
         "ArgumentUsageAttribute:Must pass an array here." ==
         "ArgumentUsageAttribute:Must pass an array here." ? True
      
      Compare a usage attribute to another usage attribute:
         "ArgumentUsageAttribute:Must pass an array here." ==
         "ArgumentUsageAttribute:Can pass param list or array here." ? False
      
      Compare an ID attribute instance to another instance of the same attribute:
         "ArgumentIDAttribute.22d1a176-4aca-427b-8230-0c1563e13187" ==
         "ArgumentIDAttribute.7fa94bba-c290-48e1-a0de-e22f6c1e64f1" ? False
      
      Compare an ID attribute to another ID attribute:
         "ArgumentIDAttribute.22d1a176-4aca-427b-8230-0c1563e13187" ==
         "ArgumentIDAttribute.b9eea70d-9c0f-459e-a984-19c46b6c8789" ? False
*/
using System;
using System.Reflection;

// Define a custom parameter attribute that takes a single message argument.
[AttributeUsage( AttributeTargets.Parameter )]
public class ArgumentUsageAttribute : Attribute
{
    // This is the attribute constructor.
    public ArgumentUsageAttribute( string UsageMsg )
    {
        this.usageMsg = UsageMsg;
    }

    // usageMsg is storage for the attribute message.
    protected string usageMsg;

    // Override ToString() to append the message to what the base generates.
    public override string ToString( )
    {
        return $"{base.ToString()}: {usageMsg}";
    }
}

// Define a custom parameter attribute that generates a GUID for each instance.
[AttributeUsage( AttributeTargets.Parameter )]
public class ArgumentIDAttribute : Attribute
{
    // This is the attribute constructor, which generates the GUID.
    public ArgumentIDAttribute( )
    {
        this.instanceGUID = Guid.NewGuid( );
    }

    // instanceGUID is storage for the generated GUID.
    protected Guid instanceGUID;

    // Override ToString() to append the GUID to what the base generates.
    public override string ToString( )
    {
        return $"{base.ToString()}.{instanceGUID.ToString()}";
    }
}

public class TestClass 
{
    // Assign an ArgumentID attribute to each parameter.
    // Assign an ArgumentUsage attribute to each parameter.
    public void TestMethod(
        [ArgumentID]
        [ArgumentUsage("Must pass an array here.")]
        String[] strArray,
        [ArgumentID]
        [ArgumentUsage("Can pass param list or array here.")]
        params String[] strList)
    { }
}

class AttributeEqualsDemo 
{
    // Create Attribute objects and compare them.
    static void Main() 
    {
        // Get the class type, and then get the MethodInfo object 
        // for TestMethod to access its metadata.
        Type clsType = typeof( TestClass );
        MethodInfo mInfo = clsType.GetMethod("TestMethod");

        // There will be two elements in pInfoArray, one for each parameter.
        ParameterInfo[] pInfoArray = mInfo.GetParameters();
        if (pInfoArray != null) 
        {
            // Create an instance of the argument usage attribute on strArray.
            ArgumentUsageAttribute arrayUsageAttr1 = (ArgumentUsageAttribute)
                Attribute.GetCustomAttribute( pInfoArray[0], 
                    typeof(ArgumentUsageAttribute) );

            // Create another instance of the argument usage attribute 
            // on strArray.
            ArgumentUsageAttribute arrayUsageAttr2 = (ArgumentUsageAttribute)
                Attribute.GetCustomAttribute( pInfoArray[0], 
                    typeof(ArgumentUsageAttribute) );

            // Create an instance of the argument usage attribute on strList.
            ArgumentUsageAttribute listUsageAttr = (ArgumentUsageAttribute)
                Attribute.GetCustomAttribute( pInfoArray[1], 
                    typeof(ArgumentUsageAttribute) );

            // Create an instance of the argument ID attribute on strArray.
            ArgumentIDAttribute arrayIDAttr1 = (ArgumentIDAttribute)
                Attribute.GetCustomAttribute( pInfoArray[0], 
                    typeof(ArgumentIDAttribute) );

            // Create another instance of the argument ID attribute on strArray.
            ArgumentIDAttribute arrayIDAttr2 = (ArgumentIDAttribute)
                Attribute.GetCustomAttribute( pInfoArray[0], 
                    typeof(ArgumentIDAttribute) );

            // Create an instance of the argument ID attribute on strList.
            ArgumentIDAttribute listIDAttr = (ArgumentIDAttribute)
                Attribute.GetCustomAttribute( pInfoArray[1], 
                    typeof(ArgumentIDAttribute) );

            // Compare various pairs of attributes for equality.
            Console.WriteLine("\nCompare a usage attribute instance to " +
                "another instance of the same attribute:" );
            Console.WriteLine($"   \"{arrayUsageAttr1}\" == \n" + 
                    $"   \"{arrayUsageAttr2}\"? {arrayUsageAttr1.Equals( arrayUsageAttr2)}");

            Console.WriteLine("\nCompare a usage attribute to " +
                "another usage attribute:" );
            Console.WriteLine($"   \"{arrayUsageAttr1}\" == \n" + 
                    $"   \"{listUsageAttr}\"? {arrayUsageAttr1.Equals(listUsageAttr)}");

            Console.WriteLine("\nCompare an ID attribute instance to " +
                "another instance of the same attribute:" );
            Console.WriteLine($"   \"{ arrayIDAttr1}\" == \n" + 
                    $"   \"{arrayIDAttr2}\"? {arrayIDAttr1.Equals(arrayIDAttr2)}");

            Console.WriteLine("\nCompare an ID attribute to another ID attribute:" );
            Console.WriteLine($"   \"{arrayIDAttr1}\" == \n" + 
                    $"   \"{listIDAttr}\"? {arrayIDAttr1.Equals(listIDAttr)}");
        }
        else
            Console.WriteLine( "The parameters information could " +
                "not be retrieved for method {0}.", mInfo.Name);
    }
    }
/*
The example displays the following output.
//         Compare a usage attribute instance to another instance of the same attribute:
//            "ArgumentUsageAttribute: Must pass an array here." ==
//            "ArgumentUsageAttribute: Must pass an array here."? True
//         
//         Compare a usage attribute to another usage attribute:
//            "ArgumentUsageAttribute: Must pass an array here." ==
//            "ArgumentUsageAttribute: Can pass param list or array here."? False
//         
//         Compare an ID attribute instance to another instance of the same attribute:
//            "ArgumentIDAttribute.22d1a176-4aca-427b-8230-0c1563e13187" ==
//            "ArgumentIDAttribute.7fa94bba-c290-48e1-a0de-e22f6c1e64f1"? False
//         
//         Compare an ID attribute to another ID attribute:
//            "ArgumentIDAttribute.22d1a176-4aca-427b-8230-0c1563e13187" ==
//            "ArgumentIDAttribute.b9eea70d-9c0f-459e-a984-19c46b6c8789"? False
*/
Imports System.Reflection

' Define a custom parameter attribute that takes a single message argument.
<AttributeUsage(AttributeTargets.Parameter)>  _
Public Class ArgumentUsageAttribute : Inherits Attribute
          
    ' This is the attribute constructor.
    Public Sub New(UsageMsg As String)
        Me.usageMsg = UsageMsg
    End Sub 

    ' usageMsg is storage for the attribute message.
    Protected usageMsg As String
           
    ' Append the message to what the base generates.
    Public Overrides Function ToString() As String
        Return $"{MyBase.ToString()}: {usageMsg}"
    End Function 
End Class 

' Define a custom parameter attribute that generates a GUID for each instance.
<AttributeUsage(AttributeTargets.Parameter)>  _
Public Class ArgumentIDAttribute : Inherits Attribute
           
    ' This is the attribute constructor, which generates the GUID.
    Public Sub New()
        Me.GUIDinstance = Guid.NewGuid()
    End Sub

    ' instanceGUID is storage for the generated GUID.
    Protected GUIDinstance As Guid
          
    ' Append the GUID to what the base generates.
    Public Overrides Function ToString() As String
        Return $"{MyBase.ToString()}.{ GUIDinstance}"
    End Function 
End Class

Public Class TestClass
    ' Assign an ArgumentID and an ArgumentUsage attribute to each parameter.
    Public Sub TestMethod( 
        <ArgumentID, ArgumentUsage("Must pass an array here.")> 
        strArray() As String, 
        <ArgumentID, ArgumentUsage("Can pass param list or array here.")> 
        ParamArray strList() As String)
    End Sub
End Class 
    
Module AttributeEqualsDemo
    Sub Main()
        ' Get the class type. 
        Dim clsType As Type = GetType(TestClass)
        ' Get the MethodInfo object for TestMethod to access its metadata.    
        Dim mInfo As MethodInfo = clsType.GetMethod("TestMethod")
                                                                                                                                   
       ' There will be two elements in pInfoArray, one for each parameter.
        Dim pInfoArray As ParameterInfo() = mInfo.GetParameters()
        If pInfoArray IsNot Nothing Then
            ' Create an instance of the argument usage attribute on strArray.
            Dim arrayUsageAttr1 As ArgumentUsageAttribute = 
                Attribute.GetCustomAttribute(pInfoArray(0), 
                    GetType(ArgumentUsageAttribute))
                 
            ' Create another instance of the argument usage attribute on strArray.
            Dim arrayUsageAttr2 As ArgumentUsageAttribute = _
                Attribute.GetCustomAttribute(pInfoArray(0), _
                    GetType(ArgumentUsageAttribute))
                 
            ' Create an instance of the argument usage attribute on strList.
            Dim listUsageAttr As ArgumentUsageAttribute = _
                Attribute.GetCustomAttribute(pInfoArray(1), _
                    GetType(ArgumentUsageAttribute))
                 
            ' Create an instance of the argument ID attribute on strArray.
            Dim arrayIDAttr1 As ArgumentIDAttribute = _
                Attribute.GetCustomAttribute(pInfoArray(0), _
                    GetType(ArgumentIDAttribute))
                 
            ' Create another instance of the argument ID attribute on strArray.
            Dim arrayIDAttr2 As ArgumentIDAttribute = _
                Attribute.GetCustomAttribute(pInfoArray(0), _
                    GetType(ArgumentIDAttribute))
              
            ' Create an instance of the argument ID attribute on strList.
            Dim listIDAttr As ArgumentIDAttribute = _
                Attribute.GetCustomAttribute(pInfoArray(1), _
                    GetType(ArgumentIDAttribute))
                 
            ' Compare various pairs of attributes for equality.
            Console.WriteLine(vbCrLf & "Compare a usage attribute instance " & _
                "to another instance of the same attribute:")
            Console.WriteLine($"   ""{arrayUsageAttr1}"" = {vbCrLf}" + 
                    $"   ""{arrayUsageAttr2}""? {arrayUsageAttr1.Equals(arrayUsageAttr2)}")  
                 
            Console.WriteLine(vbCrLf & _
                "Compare a usage attribute to another usage attribute:")
            Console.WriteLine($"   ""{arrayUsageAttr1}"" = {vbCrLf}" + 
                    $"   ""{listUsageAttr}""? {arrayUsageAttr1.Equals(listUsageAttr)}") 
                 
            Console.WriteLine(vbCrLf & "Compare an ID attribute instance " & _
                "to another instance of the same attribute:")
            Console.WriteLine($"   ""{arrayIDAttr1}"" = {vbCrLf}" +
                    $"   ""{arrayIDAttr2}""? {arrayIDAttr1.Equals(arrayIDAttr2)}")
                 
            Console.WriteLine(vbCrLf & _
                "Compare an ID attribute to another ID attribute:")
            Console.WriteLine($"   ""{arrayIDAttr1}"" ={vbCrLf}" + 
                    $"   ""{listIDAttr}"" ? {arrayIDAttr1.Equals(listIDAttr)}")
        Else
            Console.WriteLine("The parameters information could " & _
                "not be retrieved for method {0}.", mInfo.Name)
        End If
    End Sub 
End Module 
' The example displays the following output.
'     Compare a usage attribute instance to another instance of the same attribute:
'        "ArgumentUsageAttribute: Must pass an array here." =
'        "ArgumentUsageAttribute: Must pass an array here."? True
'     
'     Compare a usage attribute to another usage attribute:
'        "ArgumentUsageAttribute: Must pass an array here." =
'        "ArgumentUsageAttribute: Can pass param list or array here."? False
'     
'     Compare an ID attribute instance to another instance of the same attribute:
'        "ArgumentIDAttribute.d4f78468-f1d0-4a08-b6da-58cad249f8ea" =
'        "ArgumentIDAttribute.9b1151bd-9c87-4e9f-beb0-92375f8c24f7"? False
'     
'     Compare an ID attribute to another ID attribute:
'        "ArgumentIDAttribute.d4f78468-f1d0-4a08-b6da-58cad249f8ea" =
'        "ArgumentIDAttribute.7eba47d0-ff29-4e46-9740-e0ba05b39947"? False

備註

@No__t-0 方法會使用反映來抓取目前實例和 obj 引數的欄位資訊。The Equals method uses reflection to retrieve field information for the current instance and the obj argument. 然後,它會比較域值。It then compares field values.

在執行衍生自 Attribute 的自己類別時,您可以覆寫 Equals 方法。When implementing your own class derived from Attribute, you can override the Equals method. 由於它使用反映,因此建議您這麼做。Because it uses reflection, we recommend that you do so. 不過,您的覆寫應該執行參考相等的標準測試(這兩個引數代表相同的物件實例)或值相等(這兩個引數屬於相同類型且具有相同的域值)。However, your override should perform a standard test for reference equality (the two arguments represent the same object instance) or value equality (the two arguments are of the same type and have identical field values). 如果您想要執行自訂比較來判斷兩個屬性物件是否相等,您可以覆寫 Match 方法。If you want to perform a custom comparison to determine whether two attributes objects are equal, you can override the Match method.

適用於