VB中的一個特性

来源:互联网 发布:淘宝g家是什么牌子 编辑:程序博客网 时间:2024/04/29 05:22

有一張Form, 如圖

代碼如下:

Option Explicit
Private m_cln1 As Collection
Private m_cln2 As New Collection

'Set Nothing
Private Sub Command4_Click()
    Set m_cln1 = Nothing
    Set m_cln2 = Nothing
End Sub

'Check Cln1
Private Sub Command5_Click()
    If m_cln1 Is Nothing Then
        MsgBox ("Object is Nothing!")
    Else
        MsgBox ("Object is Not Nothing!")
    End If
End Sub

'Check Cln2
Private Sub Command6_Click()
    If m_cln2 Is Nothing Then
        MsgBox ("Object is Nothing!")
    Else
        MsgBox ("Object is Not Nothing!")
        m_cln2.Add ("Test")
        MsgBox (m_cln2.Count)
    End If
   
End Sub

'Init
Private Sub Form_Load()
    Set m_cln1 = Nothing
    Set m_cln2 = Nothing
End Sub

我們先點擊一下command4,把兩個Collection都set nothing。
這時,我們點擊Command5會出現以下對話框(圖2):

這裡理所當然的,因為我們從一開始就沒有定義過m_cln1的實例。

但如果我們點擊command6時,會出現以下地話框:

為什麼會這樣呢?我們明明把兩個collection都設為Nothing,為什麼m_Cln2不是Nothing呢?
原因是這樣的,當我們以這樣的方式定義實例時:
Private m_cln2 As New Collection
在我們一訪問cln2時,vb的runtime就會自動幫我們完成把對象實例化的功能,如下面代碼:
set m_cln2 = nothing
if m_cln2 is nothing then   '訪問m_cln2是否為空
    ...
endif
在上面紅色的代碼,其實VB的Runtime是幫我們做了以下的動作:
set m_cln2 = new collection
這裡,m_cln2已經不為空啦!

其實我們的command4的動作是成功的完成了,在按了Command4的這個時候,兩上Collection已經是為空了,只是我們在檢測m_cln2是否為空時,VB的runtime聰明的幫我們做了一些動作。

其實我們在VB的開發過程中這種情況存在嗎?答案是存在的!
好簡單,我但定議了一張新的Form2,裡面有一個對外的方法,如下:
public sub ShowMessage()
        msgbox("hello world!")
endSub

我在張Form1加上一個新的command,command的方法如下:
Private Sub Command1_Click()
    Set Form2 = Nothing
    Form2.ShowMessage
End Sub

這裡,Command1的同樣動作成功的完成了。

原创粉丝点击