Share via


如何:隱藏與您的變數名稱相同的變數 (Visual Basic)

您可以透過「遮蔽」變數 (也就是使用相同名稱的變數來重新定義變數) 以加以隱藏。 您可以透過兩種方式來遮蔽您要隱藏的變數:

  • 透過範圍遮蔽。 您可以透過範圍遮蔽變數,方法是在包含您要隱藏變數之區域的子區域內重新宣告變數。

  • 透過繼承遮蔽。 如果您要隱藏的變數是在類別層級定義,則您可以透過繼承來遮蔽變數,方法是在衍生類別中使用 Shadows 關鍵字重新宣告變數。

隱藏變數的兩種方式

透過範圍遮蔽變數來加以隱藏

  1. 判斷定義您所要隱藏變數的區域,並判斷要在其中使用您的變數來重新定義變數的子區域。

    變數的區域 允許重新定義變數的子區域
    模組 模組內的類別
    類別 類別內的子類別

    類別內的程序

    您無法在程序內的區塊中重新定義該程序變數,例如在 If...End If 建構或 For 迴圈中。

  2. 如果子區域尚未存在,請予以建立。

  3. 在子區域內,撰寫 Dim 陳述式來宣告遮蔽變數。

    當子區域內的程式碼參考變數名稱時,編譯器會解析遮蔽變數的參考。

    下列範例說明如何透過範圍遮蔽,並說明略過遮蔽的參考。

    Module shadowByScope
        ' The following statement declares num as a module-level variable.
        Public num As Integer
        Sub show()
            ' The following statement declares num as a local variable.
            Dim num As Integer
            ' The following statement sets the value of the local variable.
            num = 2
            ' The following statement displays the module-level variable.
            MsgBox(CStr(shadowByScope.num))
        End Sub
        Sub useModuleLevelNum()
            ' The following statement sets the value of the module-level variable.
            num = 1
            show()
        End Sub
    End Module
    

    上述範例會同時在模組層級和程序層級宣告變數 num (在程序 show 中)。 區域變數 num 會遮蔽 show 內的模組層級變數 num,因此區域變數會設定為 2。 不過,遮蔽 useModuleLevelNum 程序中的 num 沒有任何區域變數。 因此,useModuleLevelNum 會將模組層級變數的值設定為 1。

    show 內部的 MsgBox 呼叫會以模組名稱限定 num 來略過遮蔽機制。 因此,它會顯示模組層級變數,而不是區域變數。

透過繼承遮蔽變數來加以隱藏

  1. 確定您要隱藏的變數是以類別層級 (任何程序外部) 在類別中宣告。 否則,您就無法透過繼承來遮蔽變數。

  2. 定義衍生自變數類別的類別 (如果尚未存在)。

  3. 在衍生類別內,撰寫 Dim 陳述式來宣告您的變數。 在宣告中包含 Shadows 關鍵字。

    當衍生類別中的程式碼參考變數名稱時,編譯器會解析您變數的參考。

    下列範例說明如何透過繼承遮蔽。 它會建立兩個參考,一個存取遮蔽變數,而另一個略過遮蔽。

    Public Class shadowBaseClass
        Public shadowString As String = "This is the base class string."
    End Class
    Public Class shadowDerivedClass
        Inherits shadowBaseClass
        Public Shadows shadowString As String = "This is the derived class string."
        Public Sub showStrings()
            Dim s As String = "Unqualified shadowString: " & shadowString &
                 vbCrLf & "MyBase.shadowString: " & MyBase.shadowString
            MsgBox(s)
        End Sub
    End Class
    

    上面的範例在基底類別中宣告了變數 shadowString,並在衍生類別中遮蔽它。 衍生類別中的程序 showStrings 會在名稱 shadowString 未限定時,顯示字串的遮蔽版本。 然後在 shadowStringMyBase 關鍵字限定時,顯示已遮蔽的版本。

穩固程式設計

遮蔽引進超過一個具有相同名稱的變數版本。 當程式碼陳述式參考變數名稱時,編譯器解析參考的版本取決於程式碼陳述式的位置和限定字串是否存在等因素。 這可能會增加參考已遮蔽變數非預期版本的風險。 您可以完整限定已遮蔽變數的所有參考,來降低該風險。

另請參閱