Static (Visual Basic)Static (Visual Basic)

指定一个或多个已声明的局部变量将继续存在,并在其声明过程终止后保留其最新值。Specifies that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared.


通常,过程停止后,过程中的局部变量将立即停止存在。Normally, a local variable in a procedure ceases to exist as soon as the procedure stops. 静态变量将继续存在并保留其最新值。A static variable continues to exist and retains its most recent value. 当你的代码下一次调用该过程时,不会重新初始化该变量,并且它仍保留你分配给它的最新值。The next time your code calls the procedure, the variable is not reinitialized, and it still holds the latest value that you assigned to it. 静态变量在定义它的类或模块的生存期内继续存在。A static variable continues to exist for the lifetime of the class or module that it is defined in.


  • 声明上下文。Declaration Context. Static只能在本地变量上使用。You can use Static only on local variables. 这意味着变量的声明上下文 Static 必须是过程中的过程或块,而不能是源文件、命名空间、类、结构或模块。This means the declaration context for a Static variable must be a procedure or a block in a procedure, and it cannot be a source file, namespace, class, structure, or module.

    不能 Static 在结构过程内使用。You cannot use Static inside a structure procedure.

  • Static无法推断局部变量的数据类型。The data types of Static local variables cannot be inferred. 有关详细信息,请参阅局部类型推理For more information, see Local Type Inference.

  • 组合修饰符。Combined Modifiers. 不能 Static ReadOnly Shadows Shared 在同一声明中同时指定、或。You cannot specify Static together with ReadOnly, Shadows, or Shared in the same declaration.


在过程中声明静态变量时 Shared ,只有一个静态变量副本可用于整个应用程序。When you declare a static variable in a Shared procedure, only one copy of the static variable is available for the whole application. Shared使用类名称调用过程,而不是指向类的实例的变量。You call a Shared procedure by using the class name, not a variable that points to an instance of the class.

如果在不存在的过程中声明静态变量 Shared ,则该类的每个实例只有一个变量副本。When you declare a static variable in a procedure that isn't Shared, only one copy of the variable is available for each instance of the class. 使用指向类的特定实例的变量调用非共享过程。You call a non-shared procedure by using a variable that points to a specific instance of the class.


以下示例演示了 Static 的用法。The following example demonstrates the use of Static.

Function updateSales(ByVal thisSale As Decimal) As Decimal
    Static totalSales As Decimal = 0
    totalSales += thisSale
    Return totalSales
End Function

Static变量 totalSales 仅初始化为0次。The Static variable totalSales is initialized to 0 only one time. 每次输入时 updateSalestotalSales 仍然具有为其计算的最新值。Each time that you enter updateSales, totalSales still has the most recent value that you calculated for it.

Static可以在此上下文中使用修饰符:The Static modifier can be used in this context:

Dim 语句Dim Statement

另请参阅See also