C#对象比较的总结

时间:2021-04-29 08:13:11

简单整型比较:

从这里可以看出整型比较无论是==和Equals方法都是进行比较,比较“正常”

            int m1 = ;
int m2 = ; Console.WriteLine(m1 == m2);//值比较True
Console.WriteLine(m1.Equals(m2));//值比较True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//引用False

object比较:

类型如果是Object,进行==比较时判断的是地址是否相同,而Equals则是其虚方法判断值是否正常

            object m1 = ;
object m2 = ; Console.WriteLine(m1 == m2);//引用类型引用比较False
Console.WriteLine(m1.Equals(m2));//Object虚方法值比较True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//引用False

整型赋值比较:

这个就类似浅拷贝

            int m1 = ;
int m2 = m1; Console.WriteLine(m1 == m2);//值比较True
Console.WriteLine(m1.Equals(m2));//值比较True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//引用比较False

object和其他值类型比较:

            object m1 = ;
int m2 = ; Console.WriteLine(m1.Equals(m2));//Object虚方法值比较True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//引用False

字符串类型比较:

字符串虽然是引用类型,但是C#对其做有特殊优化,从下面的结果就可以看出,==和Equals比较的是字符串内容相同,而字符串内容相同的两个变量引用也相同,是经过运行时优化了的。

            string m1 = "tg903eiotf38";
string m2 = "tg903eiotf38"; Console.WriteLine(m1 == m2);//字符串值比较True
Console.WriteLine(m1.Equals(m2));//字符串值比较True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//字符串引用优化比较True

现有一class:

       public class Student
    {
    public long Id { get; set; }     public string Name { get; set; }
    }

引用类型比较:

简单的引用类型,==和Equals比较的是都是地址引用

       Student m1 = new Student()
{
Id = ,
Name = "朝野布告",
};
Student m2 = new Student()
{
Id = ,
Name = "朝野布告",
}; Console.WriteLine(m1 == m2);//False
Console.WriteLine(m1.Equals(m2));//False
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//False
            Student m1 = new Student()
{
Id = ,
Name = "朝野布告",
};
Student m2 = m1; Console.WriteLine(m1 == m2);//True
Console.WriteLine(m1.Equals(m2));//True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//True

引用类型赋值比较:

类似浅拷贝

            Student m1 = new Student()
{
Id = ,
Name = "朝野布告",
};
Student m2 = m1; m1.Name = "飓风"; Console.WriteLine(m1 == m2);//True
Console.WriteLine(m1.Equals(m2));//True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//True
Console.WriteLine(m1.Name);//飓风
Console.WriteLine(m2.Name);//飓风
            object m1 = new Student()
{
Id = ,
Name = "朝野布告",
};
object m2 = m1; Console.WriteLine(m1 == m2);//True
Console.WriteLine(m1.Equals(m2));//True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//True

匿名类型比较:

匿名类型==比较的是地址的引用,而哈希码的生成看的是每个数据成员的值,因此其全部值一样则哈希码一样,Equals判断也一样的道理

            var m1 = new { Id = , Name = "朝野布告" };
var m2 = new { Id = , Name = "朝野布告" }; Console.WriteLine(m1 == m2);//False
Console.WriteLine(m1.GetHashCode());//
Console.WriteLine(m2.GetHashCode());//
Console.WriteLine(m1.Equals(m2));//True
Console.WriteLine(System.Object.ReferenceEquals(m1, m2));//False