内容目录
值类型 Equals 与 == 等同;
string 经过重写, Equals 与 == 等同;
object 类型,string 的特殊性;
其他类 类型。
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 是比较是否同一对象,那么问题来了,有两种意思
是否是同一类型,还是说值相同
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();
}
}
结果 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();
}
}
Equpls 空引用会发生异常, == 不会。
Equals 与 == 区别,在于 null。
文章评论