c# - 类中通用项目的通用集合?

标签 c# .net generics .net-2.0

我正在尝试创建一个接受两种泛型类型(IQueue、IItem)的类,例如:

public class Coordinator<T,K>
    where T : IQueue<K>
    where K : IItem
{
    private T<K> collection = new T<K>();
}

地点:

public interface IQueue<T> where T : IItem
{
}

public class MyQueue<T> : IQueue<T>
    where T : IItem
{
}

但是编译器不喜欢:

private T<K> collection = new T<K>();

这有可能吗?

谢谢!

最佳答案

我认为您需要执行以下操作:

public interface IQueue<T> where T : IItem
{
}

public class MyQueue<T> : IQueue<T>
    where T : IItem
{
}

因为你在说:协调器得到一个 IQueue,但你正试图用更具体的信息构造一个 MyQueue。

使用已经讨论过的 Activator,您可以在没有编译器错误的情况下执行此操作:

class Coordinator <T,K>
    where T : IQueue<K>
    where K : IItem
{
    private T collection = (T)Activator.CreateInstance(typeof(T));
}

关于c# - 类中通用项目的通用集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6453270/

相关文章:

c# - 异步方法中的 Task.Run() 导致线程池饥饿?

c# - 如何关闭计算机?

java - 使泛型函数适用于多个非重叠类型

generics - Kotlin 泛型类重载?

c# - 图像 src 不显示处理程序提供的外部图像

c# - 有没有办法不按ALT就强制显示助记键?

c# - 如何找到实现给定接口(interface)的所有类?

c# - WinRT - TCP 客户端?

c# - `ImmutableSortedSet` 和 fsharp `Set` 有什么区别?

c# - 如何制作具有实现两个接口(interface)的类型约束的通用集合?