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
224 views
in Technique[技术] by (71.8m points)

c# - Two .NET objects that are equal don't say they are

I have the following code:

object val1 = 1;
object val2 = 1;

bool result1 = (val1 == val2);//Equals false
bool result2 = val1.Equals(val2); //Equals true

What's up with that? Is the only way to fix this to go with .Equals() method?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The operator == is static, not virtual, so the behaviour is determined by the static type and not the runtime type. The default implementation for == on objects of reference type is to compare the references (although types can implement a different behaviour, for example string). You have two different objects and they don't have the same reference so == returns false.

The solution, as you point out, is to use Equals. Equals is a virtual method. Since value1 has runtime type Int32 you end up calling Int32.Equals. From .NET Reflector you can see that the implementation of this is as follows:

public override bool Equals(object obj)
{
    return ((obj is int) && (this == ((int) obj)));
}

In other words, it checks if the argument is of type int, and if so casts it and uses the == that is defined for int. This compares the values of the integers.

Is the only way to fix this to go with .Equals() method?

An alternative is to cast your objects to int and then use ==, just as the implementation of Int32.Equals does.


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

...