Wednesday, 18 September 2013

Overriding methods with derived type

Overriding methods with derived type

I need the following inheritance:
public class Persistent
{
public virtual Persistent Clone() { ... }
}
public class Animal : Persistent
{
public override Animal Clone() { ... }
}
This can be implemented using a generic class:
public class Persistent<T>
{
public virtual T Clone() { ... }
}
public class Animal : Persistent<Animal>
{
public override Animal Clone() { ... }
}
However inheriting further from Animal does not work:
public class Pet : Animal
{
public override Pet Clone() // return type is Animal
}
Obviously Pet should derive from Persistent<Pet> for this to work but I
need classic inheritance. Unfortunately C# supports neither multiple
inheritance nor mixins. Is there any workaround?

No comments:

Post a Comment