《.Ne框架程序设计》随记(5)

实现Equals方式有3种不同的方式:

1为基类没有重写Object.Equals方法的引用类型实现Equals

None.gif class MyRefType:BaseType
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gifRefTyperefobj;
//Thisfieldisareferencetype.
InBlock.gif
ValTypevalobj;//Thisfieldisavaluetype.
InBlock.gif

InBlock.gif
publicoverrideBooleanEquals(Objectobj)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//Because’this’isn’tnull,ifobjisnull,
InBlock.gif
//thentheobjectscan’tbeequal.
InBlock.gif
if(obj==null)returnfalse;
InBlock.gif
//Iftheobjectsareofdifferenttypes,theycan’tbeequal.
InBlock.gif
if(this.GetType()!=obj.GetType())returnfalse;
InBlock.gif
//Castobjtothistypetoaccessfields.NOTE:Thiscastcan’t
InBlock.gif
//failbecauseyouknowthatobjectsareofthesametype.
InBlock.gif
MyRefTypeother=(MyRefType)obj;
InBlock.gif
//Tocomparereferencefields,dothis:
InBlock.gif
if(!Object.Equals(refobj,other.refobj))returnfalse;
InBlock.gif
//Tocomparevaluefields,dothis:
InBlock.gif
if(!valobj.Equals(other.valobj))returnfalse;
InBlock.gif
returntrue;//Objectsareequal.
ExpandedSubBlockEnd.gif
}

InBlock.gif
//Optionaloverloadsofthe==and!=operators
InBlock.gif
publicstaticBooleanoperator==(MyRefTypeo1,MyRefTypeo2)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
if(o1==null)returnfalse;
InBlock.gif
returno1.Equals(o2);
ExpandedSubBlockEnd.gif}

InBlock.gif
publicstaticBooleanoperator!=(MyRefTypeo1,MyRefTypeo2)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
return!(o1==o2);
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

None.gif

2 为基类没有重写Object.Equals方法的引用类型实现Equals方法



None.gif class MyRefType:BaseType
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gifRefTyperefobj;
//Thisfieldisareferencetype.
InBlock.gif
ValTypevalobj;//Thisfieldisavaluetype.
InBlock.gif
publicoverrideBooleanEquals(Objectobj)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//Letthebasetypecompareitsfields.
InBlock.gif
if(!base.Equals(obj))returnfalse;
InBlock.gif
//Allthecodefromheredownisidenticalto
InBlock.gif
//thatshowninthepreviousversion.
InBlock.gif
//Because’this’isn’tnull,ifobjisnull,
InBlock.gif
//thentheobjectscan’tbeequal.
InBlock.gif
//NOTE:Thislinecanbedeletedifyoutrustthat
InBlock.gif
//thebasetypeimplementedEqualscorrectly.
InBlock.gif
if(obj==null)returnfalse;
InBlock.gif
//Iftheobjectsareofdifferenttypes,theycan’tbeequal.
InBlock.gif
//NOTE:Thislinecanbedeletedifyoutrustthat
InBlock.gif
//thebasetypeimplementedEqualscorrectly.
InBlock.gif
if(this.GetType()!=obj.GetType())returnfalse;
InBlock.gif
//Castobjtothistypetoaccessfields.NOTE:Thiscast
InBlock.gif
//can’tfailbecauseyouknowthatobjectsareofthesametype.
InBlock.gif
MyRefTypeother=(MyRefType)obj;
InBlock.gif
//Tocomparereferencefields,dothis:
InBlock.gif
if(!Object.Equals(refobj,other.refobj))returnfalse;
InBlock.gif
//Tocomparevaluefields,dothis:
InBlock.gif
if(!valobj.Equals(other.valobj))returnfalse;
InBlock.gif
returntrue;//Objectsareequal.
ExpandedSubBlockEnd.gif
}

InBlock.gif
//Optionaloverloadsofthe==and!=operators
InBlock.gif
publicstaticBooleanoperator==(MyRefTypeo1,MyRefTypeo2)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
if(o1==null)returnfalse;
InBlock.gif
returno1.Equals(o2);
ExpandedSubBlockEnd.gif}

InBlock.gif
publicstaticBooleanoperator!=(MyRefTypeo1,MyRefTypeo2)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
return!(o1==o2);
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

None.gif

这里和上面唯一的差别是这里要求比较基类型中定义的字段,若基类型认为对象不相等,那么它们就不相等。

base.Equals会导致调用Object.Equals方法,那么就不应该再调用它,因为只有在两个引用指向同一个对象,Object.Equals方法才会返回true.所以,若这样,我们实现的Equals方法就会总是返回false!!

3 为值类型实现Equals方法


System.ValueType.Equals
方法在内部首先使用反射机制来得到类型所有的实例字段,然后再比较它们是否相等,这就意味着值类型继承的Equals判断的是值相等。

下面是System.ValueType.Equals方法的实现:



None.gif class ValueType
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
publicoverrideBooleanEquals(Objectobj)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//Because’this’isn’tnull,ifobjisnull,
InBlock.gif
//thentheobjectscan’tbeequal.
InBlock.gif
if(obj==null)returnfalse;
InBlock.gif
//Getthetypeof’this’object.
InBlock.gif
TypethisType=this.GetType();
InBlock.gif
//If’this’and’obj’aredifferenttypes,theycan’tbeequal.
InBlock.gif
if(thisType!=obj.GetType())returnfalse;
InBlock.gif
//Getthesetofpublicandprivateinstance
InBlock.gif
//fieldsassociatedwiththistype.
InBlock.gif
FieldInfo[]fields=thisType.GetFields(BindingFlags.Public|
InBlock.gifBindingFlags.NonPublic
|BindingFlags.Instance);
InBlock.gif
//Compareeachinstancefieldforequality.
InBlock.gif
for(Int32i=0;i<fields.Length;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//Getthevalueofthefieldfrombothobjects.
InBlock.gif
ObjectthisValue=fields[i].GetValue(this);
InBlock.gifObjectthatValue
=fields[i].GetValue(obj);
InBlock.gif
//Ifthevaluesaren’tequal,theobjectsaren’tequal.
InBlock.gif
if(!Object.Equals(thisValue,thatValue))returnfalse;
ExpandedSubBlockEnd.gif}

InBlock.gif
//Allthefieldvaluesareequal,andtheobjectsareequal.
InBlock.gif
returntrue;
ExpandedSubBlockEnd.gif}

InBlock.gif
ExpandedBlockEnd.gif}

None.gif

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

None.gif struct MyValType
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gifRefTyperefobj;
//Thisfieldisareferencetype.
InBlock.gif
ValTypevalobj;//Thisfieldisavaluetype.
InBlock.gif
publicoverrideBooleanEquals(Objectobj)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//Ifobjisnotyourtype,thentheobjectscan’tbeequal.
InBlock.gif
if(!(objisMyValType))returnfalse;
InBlock.gif
//Callthetype-safeoverloadofEqualstodothework.
InBlock.gif
returnthis.Equals((MyValType)obj);
ExpandedSubBlockEnd.gif}

InBlock.gif
//ImplementastronglytypedversionofEquals.
InBlock.gif
publicBooleanEquals(MyValTypeobj)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//Tocomparereferencefields,dothis:
InBlock.gif
if(!Object.Equals(this.refobj,obj.refobj))returnfalse;
InBlock.gif
//Tocomparevaluefields,dothis:
InBlock.gif
if(!this.valobj.Equals(obj.valobj))returnfalse;
InBlock.gif
returntrue;//Objectsareequal.
ExpandedSubBlockEnd.gif
}

InBlock.gif
//Optionallyoverloadoperator==
InBlock.gif
publicstaticBooleanoperator==(MyValTypev1,MyValTypev2)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
return(v1.Equals(v2));
ExpandedSubBlockEnd.gif}

InBlock.gif
//Optionallyoverloadoperator!=
InBlock.gif
publicstaticBooleanoperator!=(MyValTypev1,MyValTypev2)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
return!(v1==v2);
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

None.gif


一个类如果重写了Equals方法,就必须也重写GetHashCode方法,这是因为System.Collection.HashTable类的实现要求任何两个相等的对象都必须要有相同的hash码值。所以若重写了Equals方法,我们就应该重写GetHashCode方法以确保用来判等的算法和用来计算对象hash码的算法一致。


当我们向一个HashTable中添加一个/值对时,其中键对象的散列码会首先被获取,这个散列码指出了/值对应该被存储在哪个散列桶中,当HashTable对象需要查找某个时,它会取得指定键对象的散列码,然后在该散列码所标志的那个散列桶中进一步查找和指定的键对象相等的键对象。这就意味着若改变了HashTable中的一个键对象,就不能够在HashTable中找到该对象,若我们要改变一个散列表中的键对象,应该首先删除原来的/值对,然后改变键对象,最后再把新的/值对加到散列表中。

如果一个类不想作为基类被继承,又不想被实例化出对象,那么可以把类设置成sealed,并且将其构造函数的访问符设为private,定义了私有构造器就可以阻止编译器调用默认构造器,而类外也不能访问私有构造器,因此就不会新建对象。

Object
GetHashCode方法返回的是一个在应用程序域范围内确保唯一的数值,该数值在对象的整个生存期中保证不会改变,但是在对象执行垃圾收集后,这个唯一的数值可以被重新利用作为一个新的对象的散列值。而ValueTypeGetHashCode方法则使用反射来返回类型中第一个字段的散列值。

选择散列码算法,应该遵循下列原则:

1 应该使所得的数值有一个良好的随机分布

2 可以调用基类型的GetHashCode方法,将它的返回值包含在代码中,但一般情况下,不应该调用ObjectValueTypeGetHashCode方法,

3 应该至少使用一个实例字段。

4 算法中使用的字段应该是恒定不变的,也就是说在构造对象时字段被初始化后,它们就不应该再在对象的生存期内有任何改变。

5 算法应该执行的尽可能快。

6 有相同值的对象应该返回相同的散列码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值