开发者

Equals() IEquatable How ther are related to each other? [duplicate]

开发者 https://www.devze.com 2023-02-19 13:49 出处:网络
This question already has answers here: 开发者_如何学C Closed 11 years ago. Possible Duplicate: What's the difference between IEquatable and just overriding Object.Equals() ?
This question already has answers here: 开发者_如何学C Closed 11 years ago.

Possible Duplicate:

What's the difference between IEquatable and just overriding Object.Equals() ?

I know that all classes in C# are deived from object and object has a virtual method named Equals().

Why should I impliment IEquatable? Why not to override object.Equals?


IEquatable<T> defines

bool Equals(T other)

While object's Equals defines

bool Equals(object other)

So defining IEquatable for your class allows you to do an easier comparison of two items of the same class without having to cast to the current type. A lot of times you'll see people implement IEquatable and then override object's Equals to call IEquatable's equals:

public class SomeClass : IEquatable<SomeClass>
{
    public bool Equals(SomeClass other)
    {
        // actual compare
    }

    public override bool Equals(object other)
    {
        // cross-call to IEquatable's equals.
        return Equals(other as SomeClass); 
    }
}

In addition, you can define equality between other types as well. Like make Fraction implement IEquatable

0

精彩评论

暂无评论...
验证码 换一张
取 消