【问题标题】:VB.NET Conversion problem when trying to convert from base class to subclass (BC30311: "Value of type '<type1>' cannot be converted to '<type2>'")尝试从基类转换为子类时出现 VB.NET 转换问题(BC30311:“类型 '<type1>' 的值无法转换为 '<type2>'”)
【发布时间】:2010-12-17 04:15:48
【问题描述】:

请看下面的代码:

Public Sub Method(Of TEntity As EntityObject)(ByVal entity As TEntity)
    If TypeOf entity Is Contact Then  
        Dim contact As Contact = entity 'Compile error'
        Dim contact = DirectCast(entity, Contact) 'Compile error' 
        Dim contact = CType(entity, Contact) 'Compile error'
    End If
End Sub

有什么想法吗?

【问题讨论】:

    标签: vb.net type-conversion casting


    【解决方案1】:

    这不应该给你一个编译错误,应该正确地将它转换为你正在寻找的类型:

    Dim contact As Contact = TryCast(entity, Contact) 
    

    【讨论】:

    • 朋友你错了,编译错误是DirectCast函数抛出的。
    • 为什么不在发布之前尝试一下答案?
    【解决方案2】:

    以下任一作品,我想我会使用第一个:

    Dim contact As Contact = DirectCast(entity, Object) 
    Dim contact As Contact = Convert.ChangeType(entity, TypeCode.Object)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      相关资源
      最近更新 更多