Attribute.Equals(Object) Metod
Definition
Viktigt
En del information gäller för förhandsversionen av en produkt och kan komma att ändras avsevärt innan produkten blir allmänt tillgänglig. Microsoft lämnar inga garantier, uttryckliga eller underförstådda, avseende informationen som visas här.
Returnerar ett värde som anger om den här instansen är lika med ett angivet objekt.
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
Parametrar
Returer
true if obj och den här instansen är av samma typ och har identiska fältvärden, falseannars .
Exempel
I följande exempel definieras två anpassade parameterklasser Attribute och sedan skapas flera objekt för varje klass och metoden används Equals för att jämföra dem.
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
Kommentarer
Metoden Equals använder reflektion för att hämta fältinformation för den aktuella instansen obj och argumentet. Sedan jämförs fältvärden.
När du implementerar din egen klass härledd från Attributekan du åsidosätta Equals metoden. Eftersom den använder reflektion rekommenderar vi att du gör det. Åsidosättningen bör dock utföra ett standardtest för referensjämlikhet (de två argumenten representerar samma objektinstans) eller värdejämlikhet (de två argumenten är av samma typ och har identiska fältvärden). Om du vill göra en anpassad jämförelse för att avgöra om två attributobjekt är lika med, kan du åsidosätta Match metoden.