VBScript 中的 Empty, Null, "" 讨论

来源:互联网 发布:黑河学院网络管理系统 编辑:程序博客网 时间:2024/05/16 14:26
今天一个系统(ASP)忽然出了问题。原因是,原先系统里有一小段代码里关于 Request 获取的变量值的判断方法有点小问题。采用了类似如下的代码:

if IsNull(pageNumber) then
   pageNumber 
= 1
end if

而这个 pageNumber 是经过一个过滤函数输出来的。这个函数的思想大致像这样:

function GetRequest(key)
  
dim v
  v 
= Request("key")

  
if 合法(v) then
    v 
= 过滤(v) '去掉恶意干扰 sql 的一些字符
  else
    v 
= null
  
end if
  
  GetRequest 
= v
end function

在这里我想说的是,其实没有必要人为的去引入可能给我们带来大麻烦的 null 这种值。

我们可以先做一个小试验,看看 Request 得到的变量到底有哪几种可能的情况。测试代码如下:

<%
dim a, hasValue

hasValue 
= true

= Request("hello")

if IsNull(a) then
    Response.Write 
"<br>是 Null"
    hasValue = false
end if

if IsEmpty(a) then
    Response.Write 
"<br>是 Empty"
    hasValue = false
end if

if a = "" then
    Response.Write 
"<br>是空字符串"
    hasValue = false
end if

if not hasValue then Response.End
Response.Write 
"<br>有值:#" & a & "#"
%>

然后分别测试:

(a) http://localhost/test/typeCheck.asp
(b) http://localhost/test/typeCheck.asp?hello=
(c) http://localhost/test/typeCheck.asp?hello=ok

输出的结果:
(a)
是 Empty
是空字符串


(b)
是空字符串

(c)
有值:#ok#

从上面的输出可以看出,对于默认接收到的值,不管什么情况,我们都可以简单的用 = "" 这个条件来判断是否有值。
而人为的引入 null 是很不可取的做法。(这样做的弊病是跟其他地方可能存在的判断是否合法的标准不兼容,造成混淆)。正确的做法应该默认返回空字符串 ""。

简单一点讲,作为函数的返回值,应该是安全的,有效的值。

在 VBScript 中可以输出 "" 作为安全的返回值。

在 C# 中,要区分值类型和引用类型来处理。

对于值类型可输出一个默认值比如对应于整数输出 0,
引用类型输出 null 才是合理的。(表示空指针,空引用)。

还可以试试这段代码的输出结果是什么(这个没多少实际意义):

<%
if Empty = "" then
    Response.Write 
"<br>Empty = 空字符串"
else
    Response.Write 
"<br>Empty <> 空字符串"
end if

if IsEmpty(""then
    Response.Write 
"<br>IsEmpty(空字符串) = true"
else
    Response.Write 
"<br>IsEmpty(空字符串) = false"
end if
%
>