VB中判断空的几种方法,Null, Missing, Empty, Nothing, vbNullString区别
vb6中存在幾個虛幻的值:Null、Missing、Empty、Nothing、vbNullString。除了最后一個之外,每一個值都不能直接用“a=值”來判斷。下面分別解釋一下這幾個值的含義。
1、Null。
Null指一個不合法的數據,判斷一個變量是否為Null使用isNull函數。
這種數據通常出現在三種情況下:
(1)最簡單的,函數直接返回Null給調用方。譬如
Function DivideEx(ByVal A as Double, ByVal B as Double) as Double
If B=0 Then DivideEx=Null Else DivideEx=A/B
End Function這個函數在B=0時返回Null指不合法數據。
(2)數據庫中,當一個字段設為“允許空值”時,VB讀取到空值就會用Null表示。譬如
Function GetCity(rst as ADODB.Recordset) as String
If isNull(rst.Field("City")) GetCity=rst.Field("Province") Else GetCity=rst.Field("City")
End Function在這個函數中,當City字段為空時(表示所在地區為一直轄市)返回Province字段,否則返回City字段。
(3)在調用庫函數時,如果遇到傳送變量類型與定義類型不一樣時有時會出現Null值。
Null值在計算時有點奇怪,譬如Null-Null=Null,Null+10=10,Null+""=""等
2、Missing
Missing指傳遞進入Variant變量的缺少,判斷Missing使用isMissing函數。譬如
Function test(Optional a)
If isMissing(a) Then test="You don't give this the varible a." Else test="You've given this the varible a."
End
Sub Main()
Debug.Print test '->You don't give this the varible a.
Debug.Print test(123) '->You've given this the varible a.
End Sub注意,Missing只會在Varient中出現,如果給入的數據類型是Byte,Integer,Long,Single,Double等缺少時為0;String缺少時為"";Object缺少時為Nothing。
3、Enpty
Empty指一個Variant變量未初始化,判斷Empty使用isEmpty函數。譬如
Function test(a)
If isEmpty(a) Then test="a is Empty" Else test="a isn't Empty"
End Function
Sub Main()
Dim a as Variant
test(a) '->a is Empty
a=""
test(a) '->a isn't Empty
a=0
test(a) '->a isn't Empty
End Sub4、Nothing
Nothing相當于Object變量中的空值。指指向于空對象的引用。
未初始化的Object變量為Nothing;未傳入函數的Object為Nothing。判斷一個變量是否為Nothing使用 is Nothing表達式。
同時,Nothing還有另外一個用途,就是把所有指向某一個對象的Object變量賦值為Nothing可以銷毀此對象節省內存空間。
5、vbNullString
vbNullString是一個String類型的常量,通常用于傳遞一個Null給庫函數。不過很奇怪的是vbNullString=""這個表達式為True. ?
?
FROM:http://gerhut.net/blogger/2006/08/vb6nullmissingemptynothingvbnullstring.html
轉載于:https://www.cnblogs.com/zouhao/p/3664651.html
總結
以上是生活随笔為你收集整理的VB中判断空的几种方法,Null, Missing, Empty, Nothing, vbNullString区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第二章 栈和队列(1)——顺序存储
- 下一篇: Android之使用Android-AQ