[英]Generic type in generic collection
我有通用類型,看起來像:
public class GenericClass<T, U> where T : IComparable<T>
{
// Class definition here
}
然后我收集了這些實例。 通過類型約束的最簡潔方法是什么?
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]; }
}
}
有沒有更好的方法來設計這個? 我認為具體說明
GenericCollection<T, U, V> where V : GenericClass<T, U>
看起來很尷尬。 可能是我唯一的選擇....
創建泛型類時,泛型類的所有成員中使用的所有對象的所有泛型類型參數必須在編譯時可解析。
您可以將類型參數作為其他泛型類型的特定實例 - 例如:
public class GenericCollection<T> where T : GenericClass<int, string> { ... }
但是如果你希望GenericClass
的類型參數本身是通用的,那么所有這些類型都需要成為類聲明的一部分,正如你所寫:
GenericCollection<T, U, V> where V : GenericClass<T, U>
對不起,如果它看起來很尷尬,但這是你唯一的選擇。
我認為該集合需要與GenericClass相同的約束:
public class GenericCollection<T, U> where T : IComparable<T>
{
private GenericClass<T, U>[] entries;
}
我認為你的解決方案是
public class GenericClass<T, U> where T : IComparable<T>
{
// Class definition here
}
public class GenericCollection<T,U> where T : IComparable<T>
{
private GenericClass<T, U>[] entries;
public GenericClass<T, U> this[int index]
{
get{ return this.entries[index]; }
}
}
我想這就是你真正想要的......
class g<t, u> where t : IComparable<t>
{
}
class gc<t, u>
{
private g<t, u>[] entries;
public g<t, u> this[int index]
{
get { return this.entries[index]; }
}
}
你還沒有把它宣布為班級!
public class GenericCollection<V>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.