VB.Net 中函数接口参数的类型检查乐趣

问题描述 投票:0回答:1

当参数之一是接口时,Visual Studio 似乎会停止对函数参数进行类型检查。

考虑以下因素:

' An interface and the class that implements it:
Public Interface IA

End Interface

Public Class A
    Implements IA
End Class


' Another reference type for the demonstration:
Public Class MyReferenceType

End Class


' A function that uses IA as the type of one of its parameters:
Private Function SomeFunc(ByVal a As IA, ByVal r As MyReferenceType)
    Return Nothing
End Sub

这是类型检查问题的示例:

Private Sub Example()
    Dim a As IA = New A
    Dim r As New MyReferenceType

    ' Some other random reference type, choose any 
    ' other reference type you like
    Dim list As New List(Of String)

    ' Each of these calls to SomeFunc compile without errors.
    SomeFunc(r, r)
    SomeFunc(r, a)
    SomeFunc(list, r)
    SomeFunc(list, a)

    ' Does not compile due to type mismatch
    'SomeFunc(list, list)
End Sub

正如我的评论所暗示的,这段代码编译得很好,编辑器中也没有错误。如果我执行该程序,我会得到

System.InvalidCastException
,这一点也不奇怪。我猜这是编译器中的类型检查错误?我使用的是 Visual Studio 2005,那么这个问题在 VS 的更高版本中是否已修复?

.net vb.net parameters interface typechecking
1个回答
1
投票

我相信这是因为你关闭了 Option Strict。如果您一开始就打开 Option Strict,您的代码将无法编译,正如我们所期望的那样。

请注意:

SomeFunc(list, a)

不是这样的:

SomeFunc(list, list)

在第一种情况下,当 Option Strict 关闭时,编译器实际上会为您插入强制转换。毕竟,

IA
类型的值可以是
MyReferenceType

在第二种情况下,

List(Of String)
的值不能ever
MyReferenceType
兼容(有争议的
Nothing
值例外...),因此即使关闭Option Strict,编译也会失败。编译器不会让你尝试一些永远无法工作的东西。

故事的寓意:为了更好地进行类型检查,请打开 Option Strict。

© www.soinside.com 2019 - 2024. All rights reserved.