【问题标题】:Nested generic type parameters嵌套泛型类型参数
【发布时间】: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&lt;T1, T2&gt; where (your existing where clauses)这样的东西。
  • 你想要的是不可能的(几年前我一直在寻找那个)。 c#中多个类型参数必须用逗号分隔。
  • @ZoharPeled 啊,我明白了——我不喜欢ApiResponse&lt;Collection, CollectionItem&gt;,但如果没有其他办法,那就必须这样做
  • 如果您需要大致了解集合中的元素类型,那么是的,您需要这样做。

标签: c# generics inheritance interface encapsulation


【解决方案1】:

您已经在界面中为 IApiModelCollection 定义了 T,所以做这样的事情还不够吗?

ApiResponse<T> where T : IApiModelCollection<IApiModel>

我发现的另一个尝试会有点丑:

ApiResponse<T1,T2> where T1 : IApiModelCollection<T2> where T2 IApiModel

然后你会有这样的电话:

ApiResponse<Contacts<ContactDetails>, ContactDetails>

希望对你有所帮助。

【讨论】:

  • 如果T 最终被(尝试)用作IApiModelCollection&lt;SomeConcreteTypeThatImplementsIApiModel&gt;,这将不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
  • 2019-05-06
  • 2020-06-29
  • 2022-11-23
  • 2020-08-15
  • 1970-01-01
相关资源
最近更新 更多