Cannot convert type: why is it necesssary to cast twice?

后端 未结 4 1927
南旧
南旧 2020-12-10 01:13

Given this highly simplified example:

abstract class Animal { }

class Dog : Animal
{
  public void Bark() { }
}
class Cat : Animal
{
  public void Mew() { }         


        
4条回答
  •  感动是毒
    2020-12-10 01:49

    There is no explicit type conversion exist between Animal to Dog since your constrains says T must be of type Animal. Though Dog ‘Is a’ an Animal , the compiler doesn't know that T is Dog. Therefore, it doesn't let you cast.

    You can either approach this through implicit conversion

    implicit operator Animal(Dog myClass) 
    

    or can use something like below

    Dog d = _animal as Dog;
    

提交回复
热议问题