//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();
}
}
私が電話をかけているとき:
Eat<Tiger>(anAnimalThatIsATiger);
何らかの理由で as キャストが null オブジェクトを返しています。デバッガーを調べたところ、引数に渡された動物は虎を参照する動物であるのに、なぜこのキャストが私の虎を返さないのでしょうか? 現在、myDerivedAnimal にはデフォルト値 (0、null など) が入力されています。