第一个,我的代码如下:
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
当最后两个应该m_mouseEvents
和m_triadEvents
时,您将分配给所有三个If
块中的m_selectEvents
。
顺便说一句,在那里使用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
。 如果您在使用TryCast
后没有测试Nothing
那么几乎肯定您一开始就不应该使用TryCast
。 编辑:嗯...我看到您在我发布答案后/期间将TryCast
更改为DirectCast
。希望我的解释对一些有所帮助。