什么时候创建静态变量? [英] When is a static variable created?
问题描述
假设我在一个函数中有一个静态变量:
Let's say I have a static variable in a function:
Private Sub SomeFunction()
Static staticVar As String = _myField.Value
End Sub
_myField
中的值究竟何时分配给 staticVar
?在第一次调用函数时?封闭类的实例化?
When, exactly, is the value from _myField
assigned to staticVar
? Upon the first call to the function? Instantiation of the enclosing class?
推荐答案
Static
变量在赋值时被实例化,很明显.
A Static
variable is instantiated when it is assigned, obviously.
当该行运行时,不是之前,也不是之后.
When that line is run, not before, not after.
在它上面放一个断点,你就会看到.
Put a breakpoint on it and you'll see.
Static
只是意味着该值将在调用之间保持不变.
Static
just means that the value will persist between calls.
Shared
类/模块成员在第一次访问类时实例化,在任何 Shared
构造函数之前和调用之前,无论是对类构造函数还是某些共享
方法/属性.我想这可能是你困惑的根源.Static
局部变量,如 c# 中的局部 static
不是以这种方式实例化的.
Shared
class/module members are instantiated the first time the class is accessed, before any Shared
constructor and before the call, whether that is to the class constructor or some Shared
method/property. I think this may be the origin of your confusion. Static
local variables, like local static
s in c# are not instantiated in this way.
有趣的来自 Tim Schmelter 的信息,看来该值是使用隐藏的Shared
像其他Shared
类级变量一样实例化的类级变量,但始终使用默认值.
Interesting information from Tim Schmelter, it appears the value is maintained internally using a hidden Shared
class level variable that is instantiated like other Shared
class level variables but always with the default value.
开发人员观察到的效果没有变化,除了在访问类时会出现一些实例化延迟.这种延迟在实践中应该是检测不到的.
The effect observed by you the developer is unchanged, apart from some instantiation delay when the class is accessed. This delay should be undetectable in practice.
这篇关于什么时候创建静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!