c# - 无法将新实例添加到泛型类中的泛型列表。为什么?

标签 c# .net generics constraints

我有以下通用类:

public class MessageProcesser<T> where T : Message

在代码中我有以下属性:

private readonly BlockingCollection<T> _messages;

当我尝试执行此操作时出现错误(因为 T 是一条消息,所以应该是可能的):

_messages.Add(new Message(MessageType.Stop));

怎么了?

谢谢!

最佳答案

您没有消息集合。消息不能是 T,因为 T 可能已被继承。

尝试

private readonly BlockingCollection<Message> _messages;

关于c# - 无法将新实例添加到泛型类中的泛型列表。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11028817/

相关文章:

c# - Protobuf-net 尝试 JIT 编译方法 '(wrapper dynamic-method) ClassExtensions.StringArray

c# - 在 CompositeControl 中公开 OnSelectedIndexChanged 事件

c# - 如何使 System.Net.WebProxy 不绕过本地 url?

c# - RSS.NET 无法解析 feedburner 提要

c# - typeof(t).GetProperties() 当 t 是从另一个派生的接口(interface)时

c# - 使用来自数据库的 openxml 生成 excel 表

c# - 如何在 Math.NET 中从 DenseVector 初始化 Vector<double>?

.net - BlockingCollection(Of T)的目的是什么

java - 编译警告 : Unchecked call to XXX as member of the raw type

Java 泛型和模板