namespace ConsoleApp3
{
class Program
{
// Main method - entry point of program
static void Main(string[] args)
{
var animals = new Stack<Animal>();
ZooCleaner.Wash(animals);
}
}
//Simple classes declared and inherited.
public class Animal { }
public class Bear : Animal{ }
public class Camel : Animal { }
public class Stack<T> //Basic stack implementation
{
int position;
T[] data = new T[100];
public void Push(T obj) => data[position++] = obj;
public T Pop() => data[--position];
}
public class ZooCleaner
{
public static void Wash<T>(Stack<T> animals) where T:Animal
{
//Why I cannot do this? I have correctly stated that 'T' can
//be of type Animal or can derive Animal but this
//still causes compilation error!
animals.Push(new Animal()); //Error: Cannot convert from 'Animal' To Type T!!
animals.Push(new Bear()); //Error: Cannot convert from 'Bear' To Type T!!
}
}
}
问题:
在 Wash() 方法中,我正确地将通用参数“T”设置为“动物”类型或可以从“动物”派生。那么为什么我不能进行推送操作来插入 Animal 或 Bear 的对象呢?
为什么会animals.Push(new Animal()); animals.Push(new Bear());
导致编译错误?