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

// ==++== 
//
//   Copyright (c) OwnCom Corporation.  All rights reserved.
//
// ==--== 
/*==============================================================================
** 
** Class: MyRefType
**
** Purpose: 为基类没有重写Object.Equals 方法的引用类型实现Equals
**
**
=============================================================================*/
class MyRefType:BaseType
{
RefType retObj;//该字段是一个引用类型
ValueType:valObj;//该字段是一个值类型
public overide boolean Equals(object obj)
{
//如果基类有实现Equals方法
// 首先让基类型比较其中的字段
//if(!base.Equals(obj)) return false;
//如果obj 为null ,则不相等
if(obj == null) return false;
//如果两个对象的类型不相同,则不相等
if(this.GetType()!=obj.GetType()) return false;
//将obj 转换为定义的类型访问其字段。
//注意这里的转型不会失败,因为已经知道是同一个类型
MyRefType other=(MyRefType) obj;
//比较其中的引用类型的字段
if(!Object.Equals(refObj,other.refObj)) return false;
//比较其中的值类型的字段,用该字段类型的Equals方法
if(!valobj.Equals(other.valobj)) return false;
return true;
}
// 重载 ==和 != 操作符
public static boolean operator== (MyRefType o1,MyRefType o2)
{
return Object.Equals(o1,o2);
}
public static boolean operator!=(MyRefType o2,MyRefType o2)
{
return !(o1==o2);
}
}
原文地址:https://www.cnblogs.com/csharponworking/p/2029251.html