`
dato0123
  • 浏览: 914594 次
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多

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

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

classMyRefType:BaseType
{
RefTyperefobj;
//Thisfieldisareferencetype.
ValTypevalobj;//Thisfieldisavaluetype.

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

//Optionaloverloadsofthe==and!=operators
publicstaticBooleanoperator==(MyRefTypeo1,MyRefTypeo2)
{
if(o1==null)returnfalse;
returno1.Equals(o2);
}

publicstaticBooleanoperator!=(MyRefTypeo1,MyRefTypeo2)
{
return!(o1==o2);
}

}


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



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

//Optionaloverloadsofthe==and!=operators
publicstaticBooleanoperator==(MyRefTypeo1,MyRefTypeo2)
{
if(o1==null)returnfalse;
returno1.Equals(o2);
}

publicstaticBooleanoperator!=(MyRefTypeo1,MyRefTypeo2)
{
return!(o1==o2);
}

}


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

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

3 为值类型实现Equals方法


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

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



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

//Allthefieldvaluesareequal,andtheobjectsareequal.
returntrue;
}


}


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

structMyValType
{
RefTyperefobj;
//Thisfieldisareferencetype.
ValTypevalobj;//Thisfieldisavaluetype.
publicoverrideBooleanEquals(Objectobj)
{
//Ifobjisnotyourtype,thentheobjectscan’tbeequal.
if(!(objisMyValType))returnfalse;
//Callthetype-safeoverloadofEqualstodothework.
returnthis.Equals((MyValType)obj);
}

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

//Optionallyoverloadoperator==
publicstaticBooleanoperator==(MyValTypev1,MyValTypev2)
{
return(v1.Equals(v2));
}

//Optionallyoverloadoperator!=
publicstaticBooleanoperator!=(MyValTypev1,MyValTypev2)
{
return!(v1==v2);
}

}


一个类如果重写了
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 有相同值的对象应该返回相同的散列码。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics