To jest przykład tego, co Próbuję zrobić:Jak mogę poprawić ten kod: dziedziczenia i 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;
}
}
Ale jak widać powyżej, będę musiał korzystać z wielu warunkowe "jeśli", aby zidentyfikować prawdziwy typ. Problem polega na tym, że muszę użyć klasy bazowej. Na przykład:
A a = new A();
Foo foo = a;
foo.Equals(another);
Dlaczego potrzebujesz "IEquatable" w pierwszej kolejności? Nie dodaje tutaj żadnej wartości. Po prostu upewnij się, że podtypy (sensownie) zastępują również 'object.GetHashCode' oraz' object.Equals (object) ', oprócz istniejącej implementacji' IEquatable '. Wtedy otrzymasz bezpłatną wysyłkę metod wirtualnych i będzie działać w wielu innych sytuacjach. –
Ani
@Ani Czy pokażesz mi przykład? –
Hmm. Te zajęcia wydają się dziwne. Jaki jest cel Foo, ponieważ nie ma on właściwości? Również jeśli B jest po prostu A z jeszcze jedną liczbą, dlaczego nie B dziedziczy z A i po prostu dodaje Number3 zamiast z Foo? – alun