内容目录
Value type Equals and == are equivalent;
For string, after overriding, Equals and == are equivalent;
For object type, the specificity of string;
For other class types.
object t = "123";
object a = t;
object b = "123";
Console.WriteLine(a == b);
Console.ReadKey();
object t = 1;
object a = t;
object b = 1;
Console.WriteLine(a == b);
Console.ReadKey();
object t = 1;
object a = t;
object b = 1;
Console.WriteLine(a.Equals(b));
Console.ReadKey();
Equals is used to compare whether the same object, but the question arises, it has two meanings:
Is it the same type, or does it mean the values are equal?
public class Test
{
public int A { get; set; }
public int B { get; set; }
}
class Program
{
static void Main()
{
Test a = new Test { A = 1, B = 2 };
Test b = new Test { A = 2, B = 1 };
Console.WriteLine(a.Equals(b));
Console.ReadKey();
}
}
Result: False
public class Test
{
public int A { get; set; }
public int B { get; set; }
}
class Program
{
static void Main()
{
Test a = new Test { A = 1, B = 2 };
Test b = new Test { A = 1, B = 2 };
Console.WriteLine(a.Equals(b));
Console.ReadKey();
}
}
Equals will throw an exception on null reference, while == will not.
The difference between Equals and == lies in null.
文章评论