实现Equals方式有3种不同的方式:
1)为基类没有重写Object.Equals方法的引用类型实现Equals
class MyRefType : BaseType


{
RefType refobj; // This field is a reference type.
ValType valobj; // This field is a value type.

public override Boolean Equals(Object obj)

{
// Because ’this’ isn’t null, if obj is null,
// then the objects can’t be equal.
if (obj == null) return false;
// If the objects are of different types, they can’t be equal.
if (this.GetType() != obj.GetType()) return false;
// Cast obj to this type to access fields. NOTE: This cast can’t
// fail because you know that objects are of the same type.
MyRefType other = (MyRefType) obj;
// To compare reference fields, do this:
if (!Object.Equals(refobj, other.refobj)) return false;
// To compare value fields, do this:
if (!valobj.Equals(other.valobj)) return false;
return true; // Objects are equal.
}
// Optional overloads of the == and != operators
public static Boolean operator==(MyRefType o1, MyRefType o2)

{
if (o1 == null) return false;
return o1.Equals(o2);
}
public static Boolean operator!=(MyRefType o1, MyRefType o2)

{
return !(o1 == o2);
}
}

2) 为基类没有重写Object.Equals方法的引用类型实现Equals方法
class MyRefType : BaseType


{
RefType refobj; // This field is a reference type.
ValType valobj; // This field is a value type.
public override Boolean Equals(Object obj)

{
// Let the base type compare its fields.
if (!base.Equals(obj)) return false;
// All the code from here down is identical to
// that shown in the previous version.
// Because ’this’ isn’t null, if obj is null,
// then the objects can’t be equal.
// NOTE: This line can be deleted if you trust that
// the base type implemented Equals correctly.
if (obj == null) return false;
// If the objects are of different types, they can’t be equal.
// NOTE: This line can be deleted if you trust that
// the base type implemented Equals correctly.
if (this.GetType() != obj.GetType()) return false;
// Cast obj to this type to access fields. NOTE: This cast
// can’t fail because you know that objects are of the same type.
MyRefType other = (MyRefType) obj;
// To compare reference fields, do this:
if (!Object.Equals(refobj, other.refobj)) return false;
// To compare value fields, do this:
if (!valobj.Equals(other.valobj)) return false;
return true; // Objects are equal.
}
// Optional overloads of the == and != operators
public static Boolean operator==(MyRefType o1, MyRefType o2)

{
if (o1 == null) return false;
return o1.Equals(o2);
}
public static Boolean operator!=(MyRefType o1, MyRefType o2)

{
return !(o1 == o2);
}
}

这里和上面唯一的差别是这里要求比较基类型中定义的字段,若基类型认为对象不相等,那么它们就不相等。
若base.Equals会导致调用Object.Equals方法,那么就不应该再调用它,因为只有在两个引用指向同一个对象,Object.Equals方法才会返回true.所以,若这样,我们实现的Equals方法就会总是返回false!!
3) 为值类型实现Equals方法
System.ValueType.Equals方法在内部首先使用反射机制来得到类型所有的实例字段,然后再比较它们是否相等,这就意味着值类型继承的Equals判断的是值相等。
下面是System.ValueType.Equals方法的实现:
class ValueType


{
public override Boolean Equals(Object obj)

{
// Because ’this’ isn’t null, if obj is null,
// then the objects can’t be equal.
if (obj == null) return false;
// Get the type of ’this’ object.
Type thisType = this.GetType();
// If ’this’ and ’obj’ are different types, they can’t be equal.
if (thisType != obj.GetType()) return false;
// Get the set of public and private instance
// fields associated with this type.
FieldInfo[] fields = thisType.GetFields(BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance);
// Compare each instance field for equality.
for (Int32 i = 0; i < fields.Length; i++)

{
// Get the value of the field from both objects.
Object thisValue = fields[i].GetValue(this);
Object thatValue = fields[i].GetValue(obj);
// If the values aren’t equal, the objects aren’t equal.
if (!Object.Equals(thisValue, thatValue)) return false;
}
// All the field values are equal, and the objects are equal.
return true;
}
}

尽管ValueType提供了比较好的Equals实现,但我们还应该自己实现,因为这样效率比较高,并且可以避免额外的装箱操作。
struct MyValType


{
RefType refobj; // This field is a reference type.
ValType valobj; // This field is a value type.
public override Boolean Equals(Object obj)

{
// If obj is not your type, then the objects can’t be equal.
if (!(obj is MyValType)) return false;
// Call the type-safe overload of Equals to do the work.
return this.Equals((MyValType) obj);
}
// Implement a strongly typed version of Equals.
public Boolean Equals(MyValType obj)

{
// To compare reference fields, do this:
if (!Object.Equals(this.refobj, obj.refobj)) return false;
// To compare value fields, do this:
if (!this.valobj.Equals(obj.valobj)) return false;
return true; // Objects are equal.
}
// Optionally overload operator==
public static Boolean operator==(MyValType v1, MyValType v2)

{
return (v1.Equals(v2));
}
// Optionally overload operator!=
public static Boolean operator!=(MyValType v1, MyValType v2)

{
return !(v1 == v2);
}
}

一个类如果重写了Equals方法,就必须也重写GetHashCode方法,这是因为System.Collection.HashTable类的实现要求任何两个相等的对象都必须要有相同的hash码值。所以若重写了Equals方法,我们就应该重写GetHashCode方法以确保用来判等的算法和用来计算对象hash码的算法一致。
当我们向一个HashTable中添加一个“键/值对”时,其中“键对象”的散列码会首先被获取,这个散列码指出了“键/值对”应该被存储在哪个“散列桶”中,当HashTable对象需要查找某个“键”时,它会取得指定“键对象”的散列码,然后在该散列码所标志的那个“散列桶“中进一步查找和指定的”键对象“相等的键对象。这就意味着若改变了HashTable中的一个”键对象“,就不能够在HashTable中找到该对象,若我们要改变一个散列表中的”键对象“,应该首先删除原来的”键/值对“,然后改变”键对象“,最后再把新的”键/值对“加到散列表中。
如果一个类不想作为基类被继承,又不想被实例化出对象,那么可以把类设置成sealed,并且将其构造函数的访问符设为private,定义了私有构造器就可以阻止编译器调用默认构造器,而类外也不能访问私有构造器,因此就不会新建对象。
Object的GetHashCode方法返回的是一个在应用程序域范围内确保唯一的数值,该数值在对象的整个生存期中保证不会改变,但是在对象执行垃圾收集后,这个唯一的数值可以被重新利用作为一个新的对象的散列值。而ValueType的GetHashCode方法则使用反射来返回类型中第一个字段的散列值。
选择散列码算法,应该遵循下列原则:
1) 应该使所得的数值有一个良好的随机分布
2) 可以调用基类型的GetHashCode方法,将它的返回值包含在代码中,但一般情况下,不应该调用Object或ValueType的GetHashCode方法,
3) 应该至少使用一个实例字段。
4) 算法中使用的字段应该是恒定不变的,也就是说在构造对象时字段被初始化后,它们就不应该再在对象的生存期内有任何改变。
5) 算法应该执行的尽可能快。
6) 有相同值的对象应该返回相同的散列码。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述