I have a generic collection based type that holds other generic types:
class Collection<T>
{
}
class ItemType<K>
{
}
Collection<ItemType<string>> c = new Collection<ItemType<string>>();
Is there a way to specify the constraints for Collection<T> such that T is an ItemType with any type K? Sort of like this with fake syntax:
class Collection<T> where T : ItemTyp开发者_StackOverflowe<>
{
}
Yup
Depending on what you actually need, you can do:
class Collection<T>{}
class ItemTypeCollection<T> : Collection<ItemType<T>>{}
or
class Collection<TContainer,TItem>
where TContainer : ItemType<TItem>
{
}
Which one you choose depends on whether or not derivatives of ItemType<T> have different interfaces than ItemType<T>
There is one other approach as well that might work for you. But, it is a little bit more complicated.
You can create a non-generic base class or interface, such as IItemType and make the generic class ItemType<T> implement that non-generic IItemType.
Then you can write
class Collection<T>
where T: IItemType{}
Then, if your IItemType implementation is generic, you can create a Collection<ItemType<T>>. If you try to make a Collection<T> and T doesn't implement IItemType, then it will not compile
Try this:
class ItemTypeCollection<T, K> : Collection<T> where T : ItemType<K>
{
}
加载中,请稍侯......
精彩评论