关于C#的Equals
来源:百度知道 编辑:UC知道 时间:2024/06/07 00:26:38
{
public override Boolean Equals(object obj)
{
if(obj==null) return fals;
if(this.GetType()!=obj.GetType()) return fals;
MyRefType other=(MyRefType) obj;
...........
........
}
}
上面的程序中if(this.GetType()!=obj.GetType()) return fals;是判断两个对象的类型是否不同,如果不同则他们不可能相等,那么返回false; 如果相同,则执行MyRefType other=(MyRefType) obj; ;把obj转型为 MyRefType类型,但是执行MyRefType other=(MyRefType) obj之前不是已经判断两个对象的类型相同了吗,既然类型已经相同了,那怎么还需要转型呢??
MyRefType a=new MyRefType();
baseType b=new baseType();
a.Equals(b)的值不就是true了吗?可是他们是不同类型啊,一个是MyRefType类型一个是baseType类型
a.Equals(b)的值到底是不是true?
还有MyRefType other=(MyRefType) obj; 转换的是它们的确切运行时类型吗??
楼主的问题,应该这么想。
“类型已经相同了,那怎么还需要转型呢??”
首先,我认为你的程序写的有BUG,一,
if(this.GetType()!=obj.GetType()) 没这么判断的,不能用“!=”应该用“IS”啊.(为了派生类和基类的判断)
MyRefType a=new MyRefType();
baseType b=new baseType();
a.Equals(b)//这的值,按你的程序是FALSE。不是TRUE
if(this.GetType()!=obj.GetType())这句话可以说明结果是false
MyRefType other=(MyRefType) obj;这句话,那要看OBJ的类型是不是MYREFTYPE的子类的。
总之,我感觉楼主的问题,问得很乱。可能我回答的不对。请谅解了。
gettype()
表示当前实例的确切运行时类型。
备注
对于具有相同运行时类型的两个对象 x 和 y,Object.ReferenceEquals(x.GetType(),y.GetType()) 返回 true。
Type 对象公开与当前 Object 的类关联的元数据。
这些可以帮助理解
using System;
public class MyBaseClass: Object {
}
public class MyDerivedClass: MyBaseClass {
}
public class Test {
public static void Main() {
MyBaseClass myBase = new MyBaseClass();
MyDerivedClass myDerived = new MyDerivedClass();
object o = myDerived;
MyBaseClass b = myDerived;