【问题标题】:Returning Null or Nothing from VBScript function?从 VBScript 函数返回 Null 或 Nothing?
【发布时间】:2012-01-20 23:27:19
【问题描述】:

我正在尝试编写类似于下面的函数的 VBScript 等效项:

object getObject(str)
{
    if ( ... )
    {
        return object_goes_here;
    }

    return null;
}

我的猜测会在下面,除了我不理解 Nothing 和 Null 之间的区别。作为调用者,我宁愿测试返回值是使用IsNull()还是X Is Nothing设置的。

Function getObject(str)
    If ... Then
        Set getObject = object_goes_here
        Exit Function
    End If

    Set getObject = Nothing  // <-- or should this be Null?
End Function

【问题讨论】:

    标签: vbscript


    【解决方案1】:

    不返回对象的正确方法是返回Nothing 并测试Is Nothing

    VB 的Null 是Variant/Null 类型的特殊值。还有其他特殊值,例如 Variant/Empty 或 Variant/Error。它们都有自己的用途,但不是唯一的。

    【讨论】:

    • InStr 是如何摆脱它的?看起来它返回了 Nullable 的 .NET 等效项。 w3schools.com/vbscript/func_instr.asp
    • @jglouie InStr 接受 VARIANT 作为其参数,而不是对象。然后它检查VARIANT 并尝试给你你所期望的。如果字符串操作数是Null,则返回Null 是来自数据库的非常标准的常见概念。至于VB6(和VBScript)中的字符串,它们无论如何都不是对象,它们不能是Nothing。好吧,他们有点可以,但它被称为vbNullString,并且没有被Is Nothing检测到。
    【解决方案2】:

    使用第二个函数骨架。处理对象时避免 Null,因为 Set Assignment 令人讨厌。

    Dim oX : Set oX = getObject(...)
    If oX Is Nothing Then
       ...
    Else
      nice object to work with here
    End If
    

    Dim vX : vX = getObject(...) ' <-- no Set, no object
    If IsNull(vX) Then
       ...
    Else
       no object to work with here
    End If
    

    【讨论】:

      【解决方案3】:

      在您的示例代码中,对象总是得到Nothing,因为这是最后一个操作。应该是这样的:

      Function getObject(str)
           If ... Then
               Set getObject = object_goes_here
               Exit Function
           End If
           Set getObject = Nothing
      End Function
      

      或:

      Function getObject(str)
           Set getObject = Nothing  
           If ... Then
               Set getObject = object_goes_here
           End If
      End Function
      

      GSerg 的回答是正确的:你应该使用 Nothing。此外,要查看对象是否具有空引用,请使用:

      If Not object Is Nothing Then
          '  do something
      End If
      

      【讨论】:

      • 糟糕,我遗漏了 Exit Function 行,谢谢。这不是我的问题,但它会澄清任何其他搜索这个问题的人。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 2011-02-05
      • 1970-01-01
      • 2013-05-15
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多