我正在尝试编写类似于下面的函数的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
答案 0 :(得分:16)
不返回对象的正确方法是返回Nothing
并测试Is Nothing
。
VB的Null
是Variant / Null类型的特殊值。还有其他特殊值,例如Variant / Empty或Variant / Error。它们都有用,但不是那个。
答案 1 :(得分:4)
使用第二个功能骨架。处理对象时避免使用Null,因为Set Assignment憎恶。
Dim oX : Set oX = getObject(...)
If oX Is Nothing Then
...
Else
nice object to work with here
End If
VS
Dim vX : vX = getObject(...) ' <-- no Set, no object
If IsNull(vX) Then
...
Else
no object to work with here
End If
答案 2 :(得分:2)
在示例代码中,对象始终为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