VB.Net 中的隐式转换警告

Implicit conversion warning in 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

由于编译后显示warning,我修改如下图还是显示warning

在第二个 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

您在所有三个 If 块中分配给 m_selectEvents,而最后两个应该是 m_mouseEventsm_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 将 return Nothing,因此您在尝试转换后测试 Nothing。如果您在使用 TryCast 后没有测试 Nothing,那么您几乎肯定不应该一开始就使用 TryCast。 编辑:嗯...我看到您将 TryCast 更改为 DirectCast after/while 我发布了我的答案。希望我的解释对一些人有所帮助。