我有通用类型,看起来像:
public class GenericClass<T, U> where T : IComparable<T>
{
// Class definition here
}
Run Code Online (Sandbox Code Playgroud)
然后我收集了这些实例.通过类型约束的最简洁方法是什么?
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]; }
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来设计这个?我认为具体说明
GenericCollection<T, U, V> where V : GenericClass<T, U>
Run Code Online (Sandbox Code Playgroud)
看起来很尴尬.可能是我唯一的选择....
创建泛型类时,泛型类的所有成员中使用的所有对象的所有泛型类型参数必须在编译时可解析.
您可以将类型参数作为其他泛型类型的特定实例 - 例如:
public class GenericCollection<T> where T : GenericClass<int, string> { ... }
Run Code Online (Sandbox Code Playgroud)
但是如果你希望类型参数GenericClass本身是通用的,那么所有这些类型都需要成为类声明的一部分,正如你所写:
GenericCollection<T, U, V> where V : GenericClass<T, U>
Run Code Online (Sandbox Code Playgroud)
对不起,如果它看起来很尴尬,但这是你唯一的选择.
| 归档时间: |
|
| 查看次数: |
546 次 |
| 最近记录: |