泛型类型的泛型集合 [英] Generic type in generic collection
问题描述
我有泛型类型,看起来像:
I have generic type that looks like:
public class GenericClass<T, U> where T : IComparable<T>
{
// Class definition here
}
我再有这些情况的集合。什么是经过类型约束最干净的方式是什么?
I then have a collection of these instances. What is the cleanest way to pass through the type constraints?
public class GenericCollection<V> where V : GenericClass<T, U> // This won't compile
{
private GenericClass<T, U>[] entries;
public V this[index]
{
get{ return this.entries[index]; }
}
}
有可能是一个更好的方式来设计呢?我认为,指定
Is there perhaps a better way to design this? I think that specifying
GenericCollection<T, U, V> where V : GenericClass<T, U>
看起来别扭。但可能是我唯一的选择......
seems awkward. Might be my only option though....
推荐答案
在创建一个泛型类的所有的在泛型类的所有成员使用的所有对象的泛型类型参数必须可以在编译时间。
When creating a generic class, all generic type parameters of all objects used in all members of the generic class must be resolvable at compile time.
您可以拥有类型参数是的的具体的其他泛型类型的实例 - 例如:
You can have type parameters that are specific instances of other generic types - for example:
public class GenericCollection<T> where T : GenericClass<int, string> { ... }
但是,如果你想要 GenericClass
的类型参数是通用自己,那么所有这些类型的需要是类声明的一部分,因为你写的:
But if you want the type parameters of GenericClass
to be generic themselves, then all of those types need to be part of the class declaration, as you've written:
GenericCollection<T, U, V> where V : GenericClass<T, U>
很抱歉,如果看起来别扭,但是这是你唯一的选择。
Sorry if it seems awkward, but that's your only option.
这篇关于泛型类型的泛型集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!