【发布时间】:2019-03-10 20:13:03
【问题描述】:
目前,我有课:
ApiResponse<T> where T : IApiModel
如下所示:
ApiResponse<Contacts>
我想修改类型约束,让它看起来像这样:
ApiResponse<T1<T2>> where T1 : IApiModelCollection<T2> where T2 : IApiModel
然后这样调用:
ApiResponse<Contacts<ContactDetails>>
我怎样才能做到这一点?除非我指定由, 分隔的每个类型参数,否则上面的示例不起作用,例如:
ApiResponse<T1, T2>
会这样调用:
ApiResponse<Contacts, ContactDetails>
我想做的事可能吗?或者也许有更好的方法?
这是一个示例类:
public class Contacts : IApiModelCollection<ContactDetails>
{
// properties relevant to an api model collection
}
public class ContactDetails : IApiModel
{
// etc...
}
界面是这样的:
IApiModelCollection<T> where T : IApiModel
感谢任何建议
【问题讨论】:
-
你需要
ApiResponse<T1, T2> where (your existing where clauses)这样的东西。 -
你想要的是不可能的(几年前我一直在寻找那个)。 c#中多个类型参数必须用逗号分隔。
-
@ZoharPeled 啊,我明白了——我不喜欢
ApiResponse<Collection, CollectionItem>,但如果没有其他办法,那就必须这样做 -
如果您需要大致了解集合中的元素类型,那么是的,您需要这样做。
标签: c# generics inheritance interface encapsulation