Este es un ejemplo de lo que estoy tratando de hacer:¿Cómo puedo mejorar este código: Herencia y 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;
}
}
Pero como se puede ver arriba, tendría que utilizar muchos condicionales 'si' para identificar el tipo real. El problema es que tengo que usar la clase base. Por ejemplo:
A a = new A();
Foo foo = a;
foo.Equals(another);
¿Por qué necesita 'IEquatable' en primer lugar? No está agregando ningún valor aquí. Solo asegúrese de que los subtipos (con sensatez) anulen 'object.GetHashCode' y' object.Equals (object) 'también, además de la implementación existente de 'IEquatable '. Luego obtendrá el envío de métodos virtuales de forma gratuita, y funcionará en muchas más situaciones. –
Ani
@Ani ¿Me mostrarías un ejemplo? –
Hmm. Estas clases parecen extrañas. ¿Cuál es el propósito de Foo ya que no tiene propiedades? Además, si B es solo A con un Número más, ¿por qué B no hereda de A y simplemente agrega Number3 en lugar de Foo? – alun