Attribute.Equals(Object) Метод

Определение

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.

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

Параметры

obj
Object

Объект Object, который необходимо сравнить с этим экземпляром, или значение null.

Возвращаемое значение

Boolean

true, если obj и тип данного экземпляра и значения полей полностью совпадают, в противном случае false.

Примеры

В следующем примере определяются два пользовательских Attribute класса параметров, затем создается несколько объектов каждого класса и используется Equals метод для их сравнения.


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

Комментарии

EqualsМетод использует отражение для получения сведений о полях для текущего экземпляра и obj аргумента. Затем он сравнивает значения полей.

При реализации собственного класса, производного от Attribute , можно переопределить Equals метод. Так как в нем используется отражение, рекомендуется сделать это. Однако переопределение должно выполнять стандартный тест на равенство ссылок (два аргумента представляют один и тот же экземпляр объекта) или равенство значений (два аргумента имеют одинаковый тип и имеют одинаковые значения полей). Если необходимо выполнить пользовательское сравнение, чтобы определить, равны ли два объекта атрибутов, можно переопределить Match метод.

Применяется к