共用方式為


IEqualityComparer.Equals(Object, Object) 方法

定義

判斷指定的物件是否相等。

public:
 bool Equals(System::Object ^ x, System::Object ^ y);
public bool Equals (object x, object y);
public bool Equals (object? x, object? y);
abstract member Equals : obj * obj -> bool
Public Function Equals (x As Object, y As Object) As Boolean

參數

x
Object

要比較的第一個物件。

y
Object

要比較的第二個物件。

傳回

如果指定的物件相等則為 true,否則為 false

例外狀況

xy 是不同的型別,而且二者都不能處理與另外一方的比較。

範例

下列程式代碼範例示範不區分大小寫 IEqualityComparer的實作。 在此範例中 CaseInsensitiveComparer.Compare ,方法用來根據提供的 CultureInfo來判斷兩個物件是否相等。

ref class myCultureComparer : IEqualityComparer
{
private:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

    virtual bool Equals(Object^ x, Object^ y) 
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    virtual int GetHashCode(Object^ obj)
    {
        return obj->ToString()->ToLower()->GetHashCode();
    }
};
class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        return myComparer.Compare(x, y) == 0;
    }

    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}
Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return myComparer.Compare(x, y) = 0
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

備註

實作這個方法,以提供物件的自定義相等比較。

給實施者的注意事項

方法是 Equals(Object, Object) 自反、對稱和可轉移。 也就是說,如果用來比較物件本身,則傳回 ;如果是 和 y ,則傳回 ;如果是 xtruey 和 ,則傳回 true ;如果是 和 ,則為 xytruezytruezx 和 。truetruex

實作必須確定如果 Equals(Object, Object) 方法針對兩個 對象x和 傳ytrue ,則的方法x所傳回的值必須等於 傳GetHashCode(Object)回的值y

適用於