这是什么我正尝试做一个例子:如何改善这种代码:继承和IEquatable <>
public class Foo : IEquatable<Foo>
{
public bool Equals(Foo other)
{
Type type1 = this.GetType();
Type type2 = other.GetType();
if (type1 != type2)
return false;
if (type1 == typeof(A))
{
A a = (A)this;
A b = (A)other;
return a.Equals(b);
}
else if (type1 == typeof(B))
{
B c = (B)this;
B d = (B)other;
return c.Equals(d);
}
else
{
throw new Exception("Something is wrong");
}
}
}
public class A : Foo, IEquatable<A>
{
public int Number1 { get; set; }
public int Number2 { get; set; }
public bool Equals(A other)
{
return this.Number1 == other.Number1 && this.Number2 == other.Number2;
}
}
public class B : Foo, IEquatable<B>
{
public int Number1 { get; set; }
public int Number2 { get; set; }
public int Number3 { get; set; }
public bool Equals(B other)
{
return this.Number1 == other.Number1 && this.Number2 == other.Number2 && this.Number3 == other.Number3;
}
}
但是,正如你可以在上面看到,我不得不使用很多条件语句'如果'来识别真实类型。问题是我必须使用基类。例如:
A a = new A();
Foo foo = a;
foo.Equals(another);
为什么你首先需要'IEquatable'?这里没有增加任何价值。除了现有的'IEquatable ''实现之外,只要确保子类型(明智地)覆盖'object.GetHashCode'和'object.Equals(object)'。然后您可以免费获得虚拟方法调度,并且可以在更多情况下使用。 –
Ani
@Ani你能给我举个例子吗? –
嗯。这些类似乎很奇怪。 Foo的目的是什么,因为它没有任何属性?此外,如果B只是一个多一个数字为什么B不从A继承,只需添加Number3而不是Foo? – alun