请参阅下面的代码:.Equals返回意外的结果
public class ValueType<T> where T : class,new()
{
public virtual bool Equals(T other)
{
if (other == null)
return false;
Type t = GetType();
Type otherType = other.GetType();
if (t != otherType)
return false;
FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (FieldInfo field in fields)
{
object value1 = field.GetValue(other);
object value2 = field.GetValue(this);
if (value1 == null)
{
if (value2 != null)
return false;
}
else if (!value1.Equals(value2))
return false;
}
return true;
}
}
class Tiger : ValueType<Tiger> { public string name; public Tiger mother; }
class Program
{
static void Main(string[] args)
{
Tiger t1 = new Tiger() { name = "Teri" };
Tiger t2 = new Tiger() { name = "Teri" };
Tiger t3 = new Tiger() { name = "Toni", mother=t1 };
Tiger t4 = new Tiger() { name = "Toni", mother = t2 };
bool Test1 = t4.mother.Equals(t3.mother); //Highlighed line
bool Test2 = t4.Equals(t3);
}
}
我不明白为什么突出显示的行返回false。我希望它运行在一个无限循环中。
为什么你希望一个无限循环?它返回'true'顺便说一句。这是不是预料到的,因为两个母亲是平等的,他们有同样的名字,没有母亲。他们的'mother'字段返回'null',因为'Tiger'是一个引用类型(class): –
我认为他期待的!value1.Equals(value2)调用相同的等号函数 – chrispepper1989
@ chrispepper1989,是的。 +1。 – w0051977