在 VBScript 中检查 NULL 时出错

Error checking for NULL in VBScript

提问人:Vivian River 提问时间:1/25/2013 最后编辑:Vivian River 更新时间:8/13/2016 访问量:147567

问:

我在经典 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

我不断收到“Object Required”错误消息,上面写着 .If Not provider Is Nothing Then

该值要么是 NULL,要么不是 NULL,那么为什么会出现此错误?

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

ASP-Classic VBScript nullReferenceException

评论


答:

43赞 LittleBobbyTables - Au Revoir 1/25/2013 #1

从您的代码来看,它看起来像是一个变体或其他变量,而不是一个对象。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

评论

1赞 Vivian River 1/25/2013
我尝试使用,但随后该页面在线引发异常。错误显示“未设置对象变量”。If Not IsNull(provider) Thenurl = url & "&provider=" & provider
0赞 LittleBobbyTables - Au Revoir 1/25/2013
这是一个令人头疼的问题。你是传入 ,还是别的什么?vbNullprovider
1赞 LittleBobbyTables - Au Revoir 1/25/2013
我总是被教导只用于对象,试着传入。 VBScript 中的<>。NothingvbNullNothingNull
1赞 Cheran Shunmugavel 1/25/2013
使用 ,而不是 。 是与 VarType 函数一起使用的常量。NullvbNullvbNull
24赞 AutomatedChaos 1/25/2013 #2

我在评论中看到了很多混乱。,主要用于数据库处理,通常不用于 VBScript。如果调用对象/数据的文档中没有明确说明,请不要使用它。NullIsNull()vbNull

要测试变量是否未初始化,请使用 。要测试变量是未初始化还是包含 、 或 。要测试变量是否为对象,请使用 和 查看此对象是否没有参考测试。IsEmpty()""""EmptyIsObjectIs Nothing

在您的例子中,您首先要测试该变量是否为对象,然后查看该变量是否为 ,因为如果它不是对象,则在 上进行测试时会出现“Object Required”错误。NothingNothing

代码片段,以便在代码中混合搭配:

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赞 ian0411 8/13/2016 #3

我只会在变量的末尾添加一个空白 (“”) 并进行比较。即使该变量为 null,如下所示的内容也应该有效。您还可以在空格的情况下修剪变量。

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