== equals object.ReferenceEquals
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了== equals object.ReferenceEquals相关的知识,希望对你有一定的参考价值。
using System; using System.Collections.Generic; using System.Xml.Serialization; class Person { public int Age { get; set; } public string Name { get; set; } public static bool operator ==(Person p, Person pp) { return p.Equals(pp); } public static bool operator !=(Person p, Person pp) { return !(p == pp); } protected bool Equals(Person other) { return Age == other.Age && string.Equals(Name, other.Name); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Person)obj); } public override int GetHashCode() { unchecked { return (Age * 397) ^ (Name != null ? Name.GetHashCode() : 0); } } private sealed class AgeNameEqualityComparer : IEqualityComparer<Person> { public bool Equals(Person x, Person y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; if (x.GetType() != y.GetType()) return false; return x.Age == y.Age && string.Equals(x.Name, y.Name); } public int GetHashCode(Person obj) { unchecked { return (obj.Age * 397) ^ (obj.Name != null ? obj.Name.GetHashCode() : 0); } } } } class Program { static void Main(string[] args) { var pa = new Person() { Age = 32, Name = "zxl" }; var pb = new Person() { Age = 32, Name = "zxl" }; Console.WriteLine(pa == pb);//调用重载运算符== Console.WriteLine(pa.Equals(pb));//调用equals Console.WriteLine(object.ReferenceEquals(pa, pb));//比较地址 } }
以上是关于== equals object.ReferenceEquals的主要内容,如果未能解决你的问题,请参考以下文章