C# 5.0 简而言之泛型

标签 c# generics

它试图向我展示泛型如何不通过协变来确保类型安全的示例。这是示例:

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.BearTester.CamelTester.Animal 访问这些类,因为它们嵌套在测试器类。

关于C# 5.0 简而言之泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24856819/

相关文章:

c# - 绘制图表的建议

c# - 在 for 循环中创建新线程并传递参数

c# - 如何找出 map 上绘制的形状内的坐标?

c# - 通用扩展方法测试

具有 Comparable 接口(interface)的 Java 通用语法

java - 右操作数为负时位移运算符的行为

javascript - 将 javascript 双按位转换为 C#

c# - Moq - 具有通用匿名参数的设置方法

java - 使用 Stream API 进行转换

c# - 获取通用接口(interface)的实现类型