sup*_*cat 5 vb.net compiler-errors ambiguity covariance
在代码中:
Interface ISelf(Of Out TMe)
End Interface
Class SomeBase
Implements ISelf(Of SomeBase)
End Class
Class SomeDerived
Inherits SomeBase
Implements ISelf(Of SomeDerived)
End Class
Module ISelfTester
Sub TestISelf()
Dim z7 As New SomeDerived
Dim z8 As ISelf(Of SomeDerived)
Dim z9 As ISelf(Of ISelf(Of SomeDerived))
z8 = z7
z9 = z8
z9 = z7 ' Why is this illegal?
End Sub
End Module
Run Code Online (Sandbox Code Playgroud)
直接从Z7到Z9的赋值产生消息"错误13选项Strict On不允许从'wokka.SomeDerived'到'wokka.ISelf(Of Wokka.SomeDerived))的隐式转换',因为转换是模糊的".那个分配怎么比Z7到Z8,或Z8到Z9的分配更模糊?据我所知,所有三个赋值必须是表示保留转换,这意味着所有三个都必须简单地存储与Z7相同的对象的引用.
我能理解,如果我试图实例分配SomeDerived给类型的引用ISelf(Of ISelf(Of SomeBase)),试图访问该接口的成员可以从任一得到实施SomeBase或SomeDerived; 如果成员是一个返回类型的方法TMe,我可以理解这种歧义可能导致编译失败(因为编译器不知道返回类型是什么).但是,我很困惑,为什么仅仅因为"模糊性"而仅仅尝试分配引用失败,因为赋值不能被解释为除了直接存储对引用类型变量的引用之外的任何东西?
顺便说一句,预期的用法是ISelf(Of T)包含一个只读属性Self类型T,预期的实现将是Return This[表示 - 保留每种情况下的转换; 我想我应该添加一个类约束TMe,但它不会影响原始问题].如果有一个各种类哪一个是感兴趣的实施ISelf(Of theirOwnTypes),应该能够利用的协方差ISelf,以方便一些事情,否则将难以[例如,如果每个类问津的实现IMoe,ILarry和/或ICurly等.还实现了相应的类ISelfAndMoe(Of ItsOwnType),ISelfAndLarry(Of ItsOwnType)和/或ISelfAndCurly(Of ItsOwnType), etc. then one can accept a parameter type which is known to implement any combination of those interfaces e.g.ISelfAndMoe(Of ISelfAndLarry(Of ICurly))param . Given that declaration,param would implementIMoe , andparam.Self would implementILarry , andparam.Self.Self would implementICurly . Further, if the class implements the expected pattern, one could castparam to e.g.ISelfAndCurly(Of IMoe), if one wanted to call a routine which needed those two interfaces but didn't needILarry` (如果实现执行了意外的事情,这样的强制转换可能会失败,但如果对象的类遵循预期的模式,则应该成功).
Option Strict On 告诉编译器忽略简单引用到引用的隐式转换。它是隐式的,因为 z9 被允许为 aSomeBase(Of SomeBase(Of SomeDerived)并且因为SomeDerived可以替换SomeBase编译器不确定您指的是哪一个。但因为你在 z8 中明确表示它是ISelf(of SomeDerived)存在的,所以没有任何猜测。我怀疑如果你将 z9 更改为ISelf(Of SomeDerived(Of SomeDerived)这种歧义可能会消失。
然而,作为一种观点,这种嵌套会变得非常混乱,因为它会自行堆叠并且维护起来可能会成为一场噩梦。
| 归档时间: |
|
| 查看次数: |
211 次 |
| 最近记录: |