为什么用" Is"编译?但不是和#34; IsNot"?

时间:2016-03-08 20:42:48

标签: vb.net

我正在攻击一些旧的VB代码,如果发现异常,我希望函数尽早返回,但如果它是System.UnauthorizedAccessException,则该函数应该继续。我刚刚得到XY'ed,我知道这是一个奇怪的要求,但我在C#中重写代码,我只需要查看结果。我知道可能有更好的方法。这是原始代码:

Try
    doSomeStuffWithFiles(files)
Catch ex As Exception
    MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
    Exit Sub
End Try

所以我添加了几行:

Catch ex As Exception
    MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
    If TypeOf ex IsNot System.UnauthorizedAccessException Then
        Exit Sub
    End If
End Try

现在,我不是VB的专家,但据我所知,这是完全有效的VB。它还与MSDNTypeOf的示例代码完全匹配。但是,此代码无法编译。我收到这个错误:

Error   21  'Is' expected.  C:\FilePath 3114    26  Project
Error   22  'UnauthorizedAccessException' is a type in 'System' and cannot be used as an expression.    C:\FilePath 3114    32  Project

如果我将该行更改为

Catch ex As Exception
    MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
    If TypeOf ex Is System.UnauthorizedAccessException Then
        Exit Sub
    End If
End Try

然后一切都编译好了。 (没有逻辑向后)

我正在使用visual studio 2013,并以.net framework 2.0为目标。

那么IsNot无效的原因是什么?

2 个答案:

答案 0 :(得分:5)

它可以在Visual Studio 2015中使用它,但如果您查看VS2013 version of the docs,您只会看到列出的TypeOf ... Is,因此您需要使用Not TypeOf ... Is

目标.NET Framework版本并没有什么不同。如果您正在使用VS2015,TypeOf ... IsNot将会编译。

答案 1 :(得分:0)

IsNot 2.0 .Net

中不存在

VB.Net

If Not TypeOf ex Is

此语法来自vb6