在 VBScript 中检查 NULL 时出错,得到“需要对象”

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

我在经典 ASP 页面中有以下 VBScript:

function getMagicLink(fromWhere, provider)
    dim url 
    url = "magic.asp?fromwhere=" & fromWhere
    If Not provider is Nothing Then ' Error occurs here
        url = url & "&provider=" & provider 
    End if
    getMagicLink = "<a target='_blank' href='" & url & "'>" & number & "</a>"
end function

我不断收到一条“需要对象”的错误消息,上面写着

If Not provider Is Nothing Then

该值要么为 NULL,要么不为 NULL,那么为什么我会收到此错误?

编辑:当我调用该对象时,我传入 NULL,或者传入一个字符串。

vbscript null asp-classic nullreferenceexception
3个回答
43
投票

从您的代码来看,

provider
是一个变体或其他变量,而不是一个对象。

Is Nothing
仅适用于对象,但后来你说它是一个应该为NULL或NOT NULL的值,这将由
IsNull
处理。

尝试使用:

If Not IsNull(provider) Then 
    url = url & "&provider=" & provider 
End if

或者,如果这不起作用,请尝试:

If provider <> "" Then 
    url = url & "&provider=" & provider 
End if

24
投票

我在评论中看到很多混乱。

Null
IsNull()
vbNull
主要用于数据库处理,通常不在 VBScript 中使用。如果调用对象/数据的文档中没有明确说明,请勿使用它。

要测试变量是否未初始化,请使用

IsEmpty()
。要测试变量是否未初始化或包含
""
,请测试
""
Empty
。要测试变量是否是对象,请使用
IsObject
并查看该对象是否在
Is Nothing
上没有引用测试。

在您的情况下,您首先要测试变量是否是对象,然后查看该变量是否是

Nothing
,因为如果它不是对象,则在测试
 时会收到“需要对象”错误Nothing

在代码中混合和匹配的片段:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

1
投票

我将在变量末尾添加一个空格(“”)并进行比较。即使该变量为空,类似下面的内容也应该起作用。您还可以修剪变量以防空格。

If provider & "" <> "" Then 
    url = url & "&provider=" & provider 
End if
© www.soinside.com 2019 - 2024. All rights reserved.