3
I’m having a hard time accepting an inherited class as a generic class type.
public class Teste
{
private void Testando()
{
var dog = new Cachorro();
dog.Nome = "Toy";
dog.Patas = 4;
dog.MesesGestacao = 3;
dog.Especie = "Cachorro";
Animal a1 = dog;
Mamifero m1 = dog;
Pet<Animal> p1 = new Pet<Cachorro>(); // Esta linha não compila.
}
}
class Animal
{
public string Especie { get; set; }
}
class Mamifero : Animal
{
public int MesesGestacao { get; set; }
}
class Cachorro : Mamifero
{
public string Nome { get; set; }
public int Patas { get; set; }
}
class Pet<T> where T : Animal
{
public string Apelido { get; set; }
}
The mistake:
Severity Code Description Project File Line Suppression State
Error CS0029 Cannot implicitly Convert type 'Pet' to 'Pet'
But the dog is an animal...
Could help in understanding why it doesn’t work?
How could I convert a Pet<Cachorro>
in a Pet<Animal>
?