Override a property of an inherited child class with a more derived type

A simplified example of what I'm trying to achieve is as follows:

public class Animal
{
    public virtual Teeth teeth {get;set;}
}

public class Mouse : Animal
{
    public override SmallTeeth teeth {get; set;} // SmallTeeth Inherits from Teeth
}

This obviously does not work, since the teeth must be of the same type as in the Animal class, which will be overridden in the Mouse class. But can something like this be achieved when I am allowed to use a more derived type in any functions that are inherited from Animal? For example, if the Animal class contains a function for a bite:

public void Bite()
{
    teeth.bite()
    Console.WriteLine("Ouch")
} 

I could call a function Bite()inherited from Animal, and it would use a field of class Mouse of type SmallTeeth. Is it possible? and is this the best way to do what I'm trying to do? If not, what will be the right approach to this problem?

+4
2

, , , # . (++ , .)

, :

abstract class Animal
{
    public abstract Cage GetCage();
}
public class Fish : Animal
{
    public override Aquarium GetCage() { ... }
}

, , . , , , , . ? - .

, , , :

Animal animal = new Mouse();
animal.Teeth = new TRexTeeth();

, . , , .

.

, , #.

:

interface IAnimal
{
    Teeth Teeth { get; } // READ ONLY
}

class Mouse : IAnimal
{
    private SmallTeeth smallTeeth;
    public SmallTeeth Teeth 
    {
        get { return smallTeeth; }
    }

    Teeth IAnimal.Teeth { get { return this.Teeth; } }
}

, IAnimal, , , , , SmallTeeth.

:

# ?

, , , , .

# .

+10

. , generics , ( . , , ):

public class Animal<T>  where T : Teeth
{
    public virtual T teeth {get;set;}
}

public class Mouse : Animal<SmallTeeth>
{
    public override SmallTeeth teeth {get; set;} // SmallTeeth Inherits from Teeth
}
+3

Source: https://habr.com/ru/post/1629783/


All Articles