2014年1月23日 星期四

[C#] == 與 Equals() 的差異

文章連接 : stackoverflow

題目 : == 與 Equals()方法的差別
int age = 25;
short newAge = 25;
Console.WriteLine(age == newAge);  //true
Console.WriteLine(newAge.Equals(age)); //false
Console.ReadLine();
解釋 :
1. == 會轉型成int作比較。
2.Equals() 方法是型態(Type)與值(Value)都相等才會成立(true)。



Detailed answer

Primitives types override the base object.Equals(object) and return true of the boxed object is of the same type and value.
(note that it will also work for nullable types; non-null nullable types always box to an instance of the underlying type)
Since newAge is a short, its Equals(object) method only returns true if you pass a boxed shortwith the same value.
You're passing a boxed int, so it returns false.
By contrast, the == operator is defined as taking two ints (or shorts or longs).
When you call it with an int and a short, the compiler will implicitly convert the short to int and compare the resulting ints by value.

沒有留言:

張貼留言