편집

다음을 통해 공유


Attribute.Equals(Object) Method

Definition

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);
public override bool Equals (object? obj);
override this.Equals : obj -> bool
Public Overrides Function Equals (obj As Object) As Boolean

Parameters

obj
Object

An Object to compare with this instance or null.

Returns

true if obj and this instance are of the same type and have identical field values; otherwise, false.

Examples

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 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
*/
open System

// Define a custom parameter attribute that takes a single message argument.
[<AttributeUsage(AttributeTargets.Parameter)>]
type ArgumentUsageAttribute(usageMsg) =
    inherit Attribute()

    // Override ToString() to append the message to what the base generates.
    override _.ToString() =
        $"%s{base.ToString()}: %s{usageMsg}"

// Define a custom parameter attribute that generates a GUID for each instance.
[<AttributeUsage(AttributeTargets.Parameter)>]
type ArgumentIDAttribute() =
    inherit Attribute()

    let instanceGUID = Guid.NewGuid()

    // Override ToString() to append the GUID to what the base generates.
    override _.ToString() =
        $"%s{base.ToString()}: %O{instanceGUID}"
        
type TestClass() =
    // Assign an ArgumentID attribute to each parameter.
    // Assign an ArgumentUsage attribute to each parameter.
    member _.TestMethod(
        [<ArgumentID>]
        [<ArgumentUsage "Must pass an array here.">]
        strArray: string [],
        [<ArgumentID>]
        [<ArgumentUsage "Can pass param list or array here.">]
        [<ParamArray>] 
        strList: string []) = ()

// Create Attribute objects and compare them.
        
// Get the class type, and then get the MethodInfo object
// for TestMethod to access its metadata.
let clsType = typeof<TestClass>
let mInfo = clsType.GetMethod "TestMethod"

// There will be two elements in pInfoArray, one for each parameter.
let pInfoArray = mInfo.GetParameters()
if pInfoArray <> null then
    // Create an instance of the argument usage attribute on strArray.
    let arrayUsageAttr1 =
        Attribute.GetCustomAttribute(pInfoArray[0], typeof<ArgumentUsageAttribute>)
        :?> ArgumentUsageAttribute

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

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

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

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

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

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

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

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

    printfn "\nCompare an ID attribute to another ID attribute:"
    printfn $"   \"{arrayIDAttr1}\" == \n   \"{listIDAttr}\"? {arrayIDAttr1.Equals(listIDAttr)}"
else
    printfn $"The parameters information could not be retrieved for method {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

Remarks

The Equals method uses reflection to retrieve field information for the current instance and the obj argument. It then compares field values.

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). If you want to perform a custom comparison to determine whether two attributes objects are equal, you can override the Match method.

Applies to