DirectCast在编译时不接受有效的强制转换(VB.NET)

时间:2009-10-15 21:48:43

标签: vb.net casting directcast

为什么这不是有效的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

1 个答案:

答案 0 :(得分:1)

编译器无法保证T0和T1可以相互转换。例如,T0可能是某个类C0(继承自IGH_Goo),T1可能是某个类C1(也继承自IGH_Goo)。

DirectCast的规则是:其中一个类必须是另一个类的子类。这就是您的第二个示例正确验证的原因:

  • 内部DirectCast(T0 -> Object)没问题,因为T0是Object的子类。
  • 外部DirectCast(Object -> T1)没问题,因为T1是Object的子类(当然,这样的强制转换可能会在运行时失败)。

您尝试使用的DirectCast(T0 -> T1)将永远不会工作,特殊情况T0 = T1T0 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))