Visual Basic 中的存留期Lifetime in Visual Basic

已宣告專案的存留期是可供使用的時間週期。The lifetime of a declared element is the period of time during which it is available for use. 變數是唯一具有存留期的元素。Variables are the only elements that have lifetime. 基於此目的,編譯器會將程式參數和函數傳回視為變數的特殊情況。For this purpose, the compiler treats procedure parameters and function returns as special cases of variables. 變數的存留期代表它可以保存值的時間週期。The lifetime of a variable represents the period of time during which it can hold a value. 其值可能會在其存留期內變更,但一定會保留一些值。Its value can change over its lifetime, but it always holds some value.

不同的存留期Different Lifetimes

成員變數(在任何程式之外的模組層級宣告)通常與宣告它的元素具有相同的存留期。A member variable (declared at module level, outside any procedure) typically has the same lifetime as the element in which it is declared. 在類別或結構中宣告的非共用變數,會以個別複本的形式存在於其宣告所在的類別或結構的每個實例。A nonshared variable declared in a class or structure exists as a separate copy for each instance of the class or structure in which it is declared. 每個這類變數的存留期都與其實例相同。Each such variable has the same lifetime as its instance. 不過,Shared 變數只有單一存留期,這會在應用程式執行的整個時間持續發生。However, a Shared variable has only a single lifetime, which lasts for the entire time your application is running.

區域變數(在程式內宣告)只有在宣告它的程式正在執行時,才會存在。A local variable (declared inside a procedure) exists only while the procedure in which it is declared is running. 這也適用于該程式的參數和任何函式傳回。This applies also to that procedure's parameters and to any function return. 不過,如果該程式呼叫其他程式,則區域變數會在所呼叫的程式正在執行時保留其值。However, if that procedure calls other procedures, the local variables retain their values while the called procedures are running.

存留期的開頭Beginning of Lifetime

當控制項進入其宣告所在的程式時,就會開始本機變數的存留期。A local variable's lifetime begins when control enters the procedure in which it is declared. 當程式開始執行時,每個本機變數都會初始化為其資料類型的預設值。Every local variable is initialized to the default value for its data type as soon as the procedure begins running. 當此程式遇到指定初始值的 Dim 語句時,它會將這些變數設定為這些值,即使您的程式碼已將其他值指派給它們也一樣。When the procedure encounters a Dim statement that specifies initial values, it sets those variables to those values, even if your code had already assigned other values to them.

結構變數的每個成員都會初始化為另一個變數。Each member of a structure variable is initialized as if it were a separate variable. 同樣地,陣列變數的每個元素都會個別初始化。Similarly, each element of an array variable is initialized individually.

在程式內的區塊內宣告的變數(例如 For 迴圈)會在程式的進入時初始化。Variables declared within a block inside a procedure (such as a For loop) are initialized on entry to the procedure. 無論您的程式碼是否執行區塊,這些初始化都會生效。These initializations take effect whether or not your code ever executes the block.

存留期結束End of Lifetime

當程式終止時,不會保留其區域變數的值,Visual Basic 會回收其記憶體。When a procedure terminates, the values of its local variables are not preserved, and Visual Basic reclaims their memory. 下一次呼叫程式時,會再次並重新初始化其所有區域變數。The next time you call the procedure, all its local variables are created afresh and reinitialized.

當類別或結構的實例終止時,其非共用的變數會遺失其記憶體和其值。When an instance of a class or structure terminates, its nonshared variables lose their memory and their values. 類別或結構的每個新實例會建立並重新初始化其非共用的變數。Each new instance of the class or structure creates and reinitializes its nonshared variables. 不過,在應用程式停止執行之前,會保留 Shared 變數。However, Shared variables are preserved until your application stops running.

存留期的延伸Extension of Lifetime

如果您使用 Static 關鍵字來宣告區域變數,其存留期會超過其程式的執行時間。If you declare a local variable with the Static keyword, its lifetime is longer than the execution time of its procedure. 下表顯示程式宣告如何判斷 Static 變數存在的時間長度。The following table shows how the procedure declaration determines how long a Static variable exists.

程式位置和共用Procedure location and sharing 靜態變數存留期開始Static variable lifetime begins 靜態變數存留期結束Static variable lifetime ends
在模組中(預設為共用)In a module (shared by default) 第一次呼叫程式時The first time the procedure is called 當您的應用程式停止執行時When your application stops running
在類別中,Shared (程式不是實例成員)In a class, Shared (procedure is not an instance member) 第一次在特定實例或類別或結構名稱本身上呼叫程式時The first time the procedure is called either on a specific instance or on the class or structure name itself 當您的應用程式停止執行時When your application stops running
在類別的實例中,不是 Shared (程式是實例成員)In an instance of a class, not Shared (procedure is an instance member) 第一次在特定實例上呼叫程式時The first time the procedure is called on the specific instance 釋放實例以進行垃圾收集(GC)時When the instance is released for garbage collection (GC)

相同名稱的靜態變數Static Variables of the Same Name

您可以在一個以上的程式中宣告具有相同名稱的靜態變數。You can declare static variables with the same name in more than one procedure. 如果您這樣做,Visual Basic 的編譯器會將每個這類變數視為個別的元素。If you do this, the Visual Basic compiler considers each such variable to be a separate element. 對其中一個變數進行初始化並不會影響其他變數的值。The initialization of one of these variables does not affect the values of the others. 如果您定義具有一組多載的程式,並且在每個多載中宣告具有相同名稱的靜態變數,則同樣適用。The same applies if you define a procedure with a set of overloads and declare a static variable with the same name in each overload.

包含靜態變數的元素Containing Elements for Static Variables

您可以在類別內宣告靜態區域變數,也就是在該類別中的程式內。You can declare a static local variable within a class, that is, inside a procedure in that class. 不過,您不能在結構中宣告靜態區域變數,其可做為結構成員或該結構內程式的區域變數。However, you cannot declare a static local variable within a structure, either as a structure member or as a local variable of a procedure within that structure.

範例Example

描述Description

下列範例會宣告具有Static關鍵字的變數。The following example declares a variable with the Static keyword. (請注意,當Dim 語句使用如 Static的修飾詞時,您不需要 Dim 關鍵字)。(Note that you do not need the Dim keyword when the Dim Statement uses a modifier such as Static.)

程式碼Code

Function runningTotal(ByVal num As Integer) As Integer
    Static applesSold As Integer
    applesSold = applesSold + num
    Return applesSold
End Function

註解Comments

在上述範例中,變數 applesSold 會在程式 runningTotal 回到呼叫程式碼之後繼續存在。In the preceding example, the variable applesSold continues to exist after the procedure runningTotal returns to the calling code. 下次呼叫 runningTotal 時,applesSold 會保留其先前計算的值。The next time runningTotal is called, applesSold retains its previously calculated value.

如果在未使用 Static的情況下宣告 applesSold,則不會在對 runningTotal的呼叫之間保留先前的累積值。If applesSold had been declared without using Static, the previous accumulated values would not be preserved across calls to runningTotal. 下次呼叫 runningTotal 時,applesSold 會重新建立並初始化為0,而 runningTotal 只會傳回與它所呼叫的相同值。The next time runningTotal was called, applesSold would have been recreated and initialized to 0, and runningTotal would have simply returned the same value with which it was called.

編譯程式碼Compile the code

您可以初始化靜態區域變數的值,做為其宣告的一部分。You can initialize the value of a static local variable as part of its declaration. 如果您宣告要 Static的陣列,您可以初始化它的 rank (維度數目)、每個維度的長度,以及個別元素的值。If you declare an array to be Static, you can initialize its rank (number of dimensions), the length of each dimension, and the values of the individual elements.

安全性Security

在上述範例中,您可以在模組層級宣告 applesSold,以產生相同的存留期。In the preceding example, you can produce the same lifetime by declaring applesSold at module level. 不過,如果您以這種方式變更變數的範圍,此程式就不會再有獨佔存取權。If you changed the scope of a variable this way, however, the procedure would no longer have exclusive access to it. 因為其他程式可以存取 applesSold 並變更其值,所以執行總計可能不可靠,而且程式碼可能更容易維護。Because other procedures could access applesSold and change its value, the running total could be unreliable and the code could be more difficult to maintain.

請參閱See also