Equals() IEquatable How ther are related to each other? [duplicate]
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
精彩评论