为什么这不是有效的DirectCast:
Public Sub FB(OF T0 As IGH_Goo, T1 As IGH_Goo) _
(ByVal A As DataTree(Of T0), _
ByVal B As DataTree(Of T1))
Dim val_A As T1 = DirectCast(A.FirstItem, T1)
End Sub
而这是:
Public Sub FB(OF T0 As IGH_Goo, T1 As IGH_Goo) _
(ByVal A As DataTree(Of T0), _
ByVal B As DataTree(Of T1))
Dim val_A As T1 = DirectCast(DirectCast(A.FirstItem, Object), T1)
End Sub
答案 0 :(得分:1)
编译器无法保证T0和T1可以相互转换。例如,T0可能是某个类C0(继承自IGH_Goo),T1可能是某个类C1(也继承自IGH_Goo)。
DirectCast
的规则是:其中一个类必须是另一个类的子类。这就是您的第二个示例正确验证的原因:
T0 -> Object
)没问题,因为T0是Object的子类。Object -> T1
)没问题,因为T1是Object的子类(当然,这样的强制转换可能会在运行时失败)。您尝试使用的DirectCast(T0 -> T1
)将永远不会工作,特殊情况T0 = T1
或T0 inherits from T1
除外。
在第一种情况下,您的代码应该是
Public Sub FB(Of T As IGH_Goo)
(ByVal A As DataTree(Of T), ByVal B As DataTree(Of T))
或者,在第二种情况下(也适用于第一种情况):
Public Sub FB(OF T0 As T1, T1 As IGH_Goo)
(ByVal A As DataTree(Of T0), ByVal B As DataTree(Of T1))