VB.Net中的隐式转换警告

时间:2017-03-31 06:41:32

标签: vb.net object compiler-warnings implicit-conversion

第一个,我的代码如下:

    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。这有什么不同吗?我的代码出错了请告诉我如何隐藏警告?

提前致谢。

    Dim eventType As Object = Nothing

    eventType = GetEventType()

    If Not (eventType Is Nothing) Then

        If TypeOf eventType Is ClassSelectEvents Then
            'm_selectEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassSelectEvents)
            m_selectEvents = DirectCast(eventType, ClassSelectEvents)
        End If

        If TypeOf eventType Is ClassMouseEvents Then
            'm_mouseEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassMouseEvents)  ' Warning BC42016: Implicit type conversion from 'ClassMouseEvents' to 'ClassSelectEvents'.
            m_selectEvents = DirectCast(eventType, ClassMouseEvents)    ' Warning BC42016: Implicit type conversion from 'ClassMouseEvents' to 'ClassSelectEvents'.
        End If

        If TypeOf eventType Is ClassTriadEvents Then
            'm_triadEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassTriadEvents)  ' Warning BC42016: Implicit type conversion from 'ClassTriadEvents' to 'ClassSelectEvents'.
            m_selectEvents = DirectCast(eventType, ClassTriadEvents)    ' Warning BC42016: Implicit type conversion from 'ClassTriadEvents' to 'ClassSelectEvents'.
        End If

    End If

1 个答案:

答案 0 :(得分:1)

当最后两个m_selectEventsIf时,您将在所有三个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
如果演员表失败,

TryCast将返回Nothing,因此您在尝试演员后测试Nothing。如果您在使用Nothing后未对TryCast进行测试,那么您几乎肯定不应该使用TryCast开头。  编辑:嗯......我看到你在我发布答案后/之后将TryCast更改为DirectCast。希望无论如何我的解释都有所帮助。