为什么我在 C# 中使用泛型出现编译错误

Why i get compilation error in C# with generic

我有包含参数 BlockingCollection<T> 队列的方法,并且 T 必须扩展我的 class QueueItem(没有泛型也能正常工作)。

private void ProcessQueue<T>(BlockingCollection<T> queue) where T: QueueItem
{
     QueueItem frame;
     while (true)
     {
          if (queue.TryTake(out frame, -1))
          {
              frame.execute();
          }
     }
}

if (queue.TryTake(out frame, -1)) 上的编译错误:“该方法有一些无效参数

为什么?

编辑方法定义为:

BlockingCollection<T> TryTake(T, Int32)

frame 应该是 T 但您提供的是 QueueItem。更改 frame 的类型:

 T frame;
 while (true)
 {
      if (queue.TryTake(out frame, -1))
      {
          frame.execute();
      }
 }