//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();
}
}
내가 전화를 만들고있어 실패. 나는 디버거를 살펴 봤는데 인수로 전달 된 동물은 호랑이에 대한 참조가있는 동물이므로이 캐스팅이 내 호랑이를 돌려주지 않는 이유는 무엇입니까? 현재 myDerivedAnimal은 기본값 (0, null 등)으로 채워져 있습니다. 이 Animal
을 상속하도록 제약 조건을 강제일반적인 방법은 명시 적 캐스트
protected virtual void Eat<AnimalType>(AnimalType animal)
where AnimalType : Animal
:
'AnimalType : Animal'을 사용하여 제네릭을 잘못 사용하면'Animal' 만 얻습니다. – gdoron
만약'animal as AnimalType'을 캐스팅했다면 메소드 시그니처를'protected virtual void Eat (AnimalType animal)으로 변경하는 것이 더 좋을 것입니다. AnimalType : Animal'? –
MarioVW