开发者社区 问答 正文

VB.Net中的隐式转换警告

首先,我的代码如下:

Dim eventType As Object = Nothing

    eventType = GetEventType()

    If Not (eventType Is Nothing) Then

        If TypeOf eventType Is ClassSelectEvents Then
            m_selectEvents = eventType  ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassSelectEvents'.
        End If

        If TypeOf eventType Is ClassMouseEvents Then
            m_mouseEvents = eventType   ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassMouseEvents'.
        End If

        If TypeOf eventType Is ClassTriadEvents Then
            m_triadEvents = eventType   ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassTriadEvents'.
        End If

    End If

由于在编译器之后显示警告,因此如下所示对其进行了修改,但仍显示警告。

在第二个If语句中,我认为类型eventType为Object。那不一样吗 我的代码哪里错了请告诉我如何隐藏警告?

展开
收起
游客ufivfoddcd53c 2020-01-04 14:04:16 1080 分享 版权
1 条回答
写回答
取消 提交回答
  • 您要分配给m_selectEvents所有三个If块,最后两个应该是m_mouseEvents和m_triadEvents。

    顺便说一句,这里没有意义TryCast,因为您的If声明已经保证了强制转换将起作用。您应该只使用DirectCast。如果您想使用,TryCast则可以这样做:

    m_selectEvents = TryCast(eventType, ClassSelectEvents)
    
    If m_selectEvents Is Nothing Then
        m_mouseEvents = DirectCast(eventType, ClassMouseEvents)
    
        If m_mouseEvents Is Nothing Then
            m_triadEvents = DirectCast(eventType, ClassTriadEvents)
        End If
    End If
    
    

    TryCastNothing如果投放失败,将会返回,因此您Nothing尝试投放后进行测试。如果您Nothing在使用后不进行测试,TryCast那么几乎可以肯定不应该使用TryCast它。编辑:嗯...我看到您在发布我的答案后更改TryCast为DirectCast。希望我的解释无论如何都会有所帮助。

    2020-01-04 14:04:34
    赞同 展开评论
问答分类:
问答标签:
问答地址: