Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

.net - C#: Default implementation for == and != operators for objects

I'd like to know what is default implementation for equality operatort (== and !=)

Is it?

public static bool operator ==(object obj1, object obj2)
{
    return obj1.Equals(obj2);
}
public static bool operator !=(object obj1, object obj2)
{
    return !obj1.Equals(obj2);
}

So I only need to override Equals method or do I need to override euality operators as well ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, it's not that - by default, references are checked for equality. Operators such as == are not polymorphic and don't call anything polymorphic by default. So for example:

string x = "Hello";
string y = new String("Hello".ToCharArray());
Console.WriteLine(x == y); // True; uses overloaded operator

object a = x;
object b = y;
Console.WriteLine(a == b); // False; uses default implementation

You can't override equality operators, but you can overload them, as string does. Whether or not you should is a different matter. I think I usually would if I were overriding Equals, but not necessarily always.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...