【问题标题】:Testing if object Is Nothing results in 'Object required' error测试对象是否为空会导致“需要对象”错误
【发布时间】:2012-03-13 15:10:02
【问题描述】:

我支持一些经典的 ASP 页面,其中一个使用和重用对象 conn 并在 .asp 页面完成处理时或页面重定向到另一个页面之前将其处理掉.

<%
dim conn
...
set conn = server.CreateObject("adodb.connection")
...
sub cleanUp()
    conn.Close
    set conn = nothing
end sub
...
sub pageRedirect(url)
    call cleanUp()
    response.Redirect url : response.End
end sub
...
' very end of file
call cleanUp()%>

我发现如果有重定向,我会在conn.Close 行收到服务器错误,Microsoft VBScript 运行时错误'800a01a8' Object required。我认为该行没有理由多次执行,但为了安全起见,我重写了函数

sub cleanUp()
    if(not (conn Is Nothing)) then
        conn.Close
        set conn = Nothing
    end if
end sub

但我仍然得到那个确切的错误,现在在if(not (conn Is Nothing)) 行!我认为Is Nothing 的目的是在使用变量名 conn 之前进行测试,以防止出现“需要对象”错误,但测试抛出了同样的错误。

如果 conn 已经设置为 Nothing,我可以使用什么其他测试来确保不引用它?

【问题讨论】:

  • if条件后给空间"if (not ("
  • Empty 用于值变量,Nothing 用于对象。 conn 是一个对象。间距并不重要。

标签: asp-classic vbscript


【解决方案1】:

is nothing 用于测试对象引用,如果变量不包含此类,则测试无效并引发错误,因此 conn 只能在 set 对某物进行测试后进行测试。

你可以;

if isobject(conn) then
   if not (conn Is Nothing) then set conn = nothing
end if

【讨论】:

  • 感谢这对我有用。在声明对象后立即将它们设置为空也是一个好主意。
【解决方案2】:
  1. 使用显式选项(每次在没有显式选项的情况下运行脚本时,都会有一只小狗死在那里),正如 Nilpo 所提到的,您可能早就发现了这个问题。
  2. 当您将要用作对象引用的变量变暗并在 Nothing 上对其进行测试时,请养成在初始化时将其设置为 Nothing (*) 的习惯:dim myObject : Set myObject = Nothing

(*) 不是在初始化时,因为在例程开始之前处理了 dim,但是当你将所有的 dim 放在例程的顶部时,它实际上是相同的。

【讨论】:

    【解决方案3】:

    使用IsNothing 函数。您还应该检查它是否是一个对象。

    sub cleanUp()
        if Not IsNothing(conn) then
            if IsObject(conn) then
                conn.Close
            end if
            set conn = nothing
        end if
    end sub
    

    话虽如此,我会这样做,因为将变量设置为空无害。

    sub cleanUp()
        if IsObject(conn) then
            conn.Close
        end if
        set conn = nothing
    end sub
    

    更重要的是,您的问题是 conn 不在您的子例程的范围内。您可能应该将其作为参数传递。

    【讨论】:

    • IsNothing 函数有参考吗?
    • 没有IsNothing函数。声明中必须使用Is Nothing,如:if obj Is Nothing then ' do stuff end if
    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 2022-11-04
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    相关资源
    最近更新 更多