【发布时间】:2014-01-02 09:25:13
【问题描述】:
我正在尝试像这样将两个接口链接在一起:
Public Interface A(Of Out T As B(Of A(Of T)))
...
End Interface
Public Interface B(Of Out T As A(Of B(Of T)))
...
End Interface
问题是我收到错误“类型参数A(Of T) 不继承或实现约束类型A(Of B(Of A(Of T)))”,但为什么不呢?
T 确实继承自 B(Of A(Of T)) 并且是 Out 泛型类型,对吧?
更新:这种构造的原因是,在实现 A 时,我希望通过将类型参数 T 设置为接口B 带有类型参数的原始类,像这样:
Class AA
Implements A(Of BB)
...
End Class
Class BB
Implements B(Of AA)
...
End Class
每个接口将具有一个功能:
Public Interface A(Of Out T As B(Of A(Of T)))
Function getB() As T
End Interface
Public Interface B(Of Out T As A(Of B(Of T)))
ReadOnly Property myA As T
End Interface
函数getB返回B的一个实例,函数myA返回A的链接实例。也许还有另一种设计方法,但我仍然想知道我得到的错误实际上意味着什么。希望有人明白我为什么会收到这个错误。
【问题讨论】:
-
也许如果您能解释实现这些接口的两个类之间的关系意味着什么,我们或许可以建议正确的注释(或告诉您您要强制执行的内容)在泛型中不可强制执行)
-
我认为您试图实现的目标在泛型中无法执行 - 它似乎 类似于 与 Eric Lippert 的 Curiouser and curiouser blog post 中给出的示例(它是 C# 但相同限制适用于 VB)
-
我提供的答案确实为您提供了您想要的东西。您可以一直保持强类型的双递归类结构。
标签: .net vb.net generics inheritance constraints