[英]Generic collection of generic items in a class?
I'm trying to create a class that accepts two generic types (IQueue, IItem) for example: 我正在尝试创建一个接受两种泛型类型的类(IQueue,IItem),例如:
public class Coordinator<T,K>
where T : IQueue<K>
where K : IItem
{
private T<K> collection = new T<K>();
}
Where: 哪里:
public interface IQueue<T> where T : IItem
{
}
public class MyQueue<T> : IQueue<T>
where T : IItem
{
}
But the compiler does not like: 但编译器不喜欢:
private T<K> collection = new T<K>();
Is this at all possible? 这是可能吗?
Thanks! 谢谢!
I think you need to do the following: 我想你需要做以下事情:
public interface IQueue<T> where T : IItem
{
}
public class MyQueue<T> : IQueue<T>
where T : IItem
{
}
Because you are saying: The coordinator gets an IQueue, but you are trying to construct a MyQueue with more specific information. 因为您说:协调员获得IQueue,但您正在尝试使用更具体的信息构建MyQueue。
Using the already discussed Activator
, you can do this without compiler errors: 使用已经讨论的
Activator
,您可以在没有编译器错误的情况下执行此操作
class Coordinator <T,K>
where T : IQueue<K>
where K : IItem
{
private T collection = (T)Activator.CreateInstance(typeof(T));
}
I think you might have expected that in "where T : IQueue where K : IItem" there was a sequence, however it actually needs to be explicity defined now . 我想你可能已经预料到“在哪里T:IQueue其中K:IItem”有一个序列,但它实际上需要现在明确定义。 It would be a nice feature if this did work in the future though.
如果这在将来确实有用,那将是一个很好的功能。 Intuitively what you ask makes sense to me.
直觉上你的要求对我有意义。
here's a suggested way to approach it. 这是建议的方法来接近它。
public class Coordinator<T> where T : IQueue<T>, new()
{
private T collection = new T();
}
public interface IQueue<T>{}
public interface IItem{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.