Attribute.Equals(Object) Methode

Definition

Gibt einen Wert zurück, der angibt, ob diese Instanz gleich einem angegebenen Objekt ist.

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

Parameter

obj
Object

Ein Object, das mit dieser Instanz oder null verglichen werden soll.

Gibt zurück

Boolean

Wenn obj und diese Instanz vom selben Typ sind und über identische Feldwerte verfügen: true, andernfalls false.

Beispiele

Im folgenden Beispiel werden zwei benutzerdefinierte Parameterklassen definiert, anschließend werden mehrere Objekte jeder Klasse erstellt und mit der Attribute Equals -Methode verglichen.


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 an output similar to the following:
      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 an output similar to the following:
//         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 an output similar to the following:
'     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

Hinweise

Die Equals -Methode verwendet Reflektion, um Feldinformationen für die aktuelle Instanz und das Argument obj abzurufen. Anschließend werden Feldwerte verglichen.

Wenn Sie eine eigene klasse implementieren, die von abgeleitet Attribute ist, können Sie die -Methode Equals überschreiben. Da die Reflektion verwendet wird, wird empfohlen, dies zu tun. Ihre Außerkraftsetzung sollte jedoch einen Standardtest auf Verweisgleichheit (die beiden Argumente stellen die gleiche Objektinstanz dar) oder Wertgleichheit (die beiden Argumente sind vom gleichen Typ und haben identische Feldwerte) durchführen. Wenn Sie einen benutzerdefinierten Vergleich durchführen möchten, um zu bestimmen, ob zwei Attributobjekte gleich sind, können Sie die -Methode Match überschreiben.

Gilt für