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

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

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

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

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

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

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

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

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

posted on 2006-09-06 23:54  Phinecos(洞庭散人)  阅读(331)  评论(0编辑  收藏  举报

导航