它试图向我展示泛型如何不通过协变来确保类型安全的示例。这是示例:
class Animal{}
class Bear : Animal {}
class Camel : Animal {}
public class Stack<T> /// a simple stack implementation
{
int position;
T[] Data = new T[100];
public void Push (T obj) { data[position++] = obj;}
public T Pop() { return data[--position] }
}
Stack<Bear> bears = new Stack<Bear>();
Stack<Animal> animals = bears; ////COMPILE-TIME ERROR
这就是目的。它还继续显示 animals.Push (new Camel());
是不可能的,当我尝试运行相同的代码以查看发生了什么时,我得到了一组不同的错误.我想这是因为我不明白如何实际运行代码。
namespace C.Fiddle
{
class Program
{
static void Main(string[] args)
{
Tester.Stack<Bear> bears = new Tester.Stack<Bear>();
Tester.Stack<Animal> animals = bears;
animals.Push(new Camel());
}
}
}
public class Tester
{
public class Stack<T>
{
int position;
T[] data = new T[10];
public void Push(T obj) { data[position++] = obj; }
public T Pop() { return data[position--]; }
}
public class Animal { }
public class Bear : Animal { }
public class Camel : Animal { }
public class ZooCleaner
{
private static void Wash<T> (Stack<Animal> animals) where T: Animal {}
}
}
错误是:
The type or namespace Bear could not be found (x2)
The type or namespace Animal could not be found
The type or namespace Camel could not be found
Cannot implicity convert type 'Tester.Stack' to Tester.Stack'
最后一个是我要查找的错误。我做错了什么?
最佳答案
您可以使用 Tester.Bear
、Tester.Camel
和 Tester.Animal
访问这些类,因为它们嵌套在测试器
类。
关于C# 5.0 简而言之泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24856819/