通用方法失败显式转换

Pat*_*.SE 0 c#

//I know for sure that the animal being passed is a Tiger
protected virtual void Eat<AnimalType>(Animal animal)
where AnimalType : Animal
 {
   //The animal type is a Tiger type.
   //Should be equivalent to :
   //Tiger myDerivedAnimal = animal as Tiger;
   AnimalType myDerivedAnimal = animal as AnimalType;

   if (myDerivedAnimal != null)
   {
       myDerivedAnimal.eat();
   }
}
Run Code Online (Sandbox Code Playgroud)

当我打电话时:

Eat<Tiger>(anAnimalThatIsATiger);
Run Code Online (Sandbox Code Playgroud)

由于某种原因,as cast返回了我的null对象.我已经通过调试器看了一下,通过参数的动物是一只参考老虎的动物,那么为什么这个演员没能归还我的老虎?截至目前,myDerivedAnimal填充了默认值(0,null等).

Jus*_*ony 7

这不是泛型如何工作,你想要更像这样的东西:

protected virtual void Eat<AnimalType>(AnimalType animal)
where AnimalType : Animal
Run Code Online (Sandbox Code Playgroud)

约束将强制它以便继承Animal.请注意,参数类型已更改AnimalAnimalType

但是,你甚至不需要代码外观的泛型.您可以在其根目录中使用继承并调用

animal.Eat()
Run Code Online (Sandbox Code Playgroud)

这可能是因为SO的简化,所以至少你不需要演员,因为这是由通用本身来处理的:

protected virtual void Eat<AnimalType>(AnimalType animal)
    where AnimalType : Animal
 {
   if(animal == null) return;
   animal.eat();
}
Run Code Online (Sandbox Code Playgroud)