When is a static variable created?

前端 未结 3 1131
耶瑟儿~
耶瑟儿~ 2020-12-19 11:02

Let\'s say I have a static variable in a function:

Private Sub SomeFunction()
    Static staticVar As String = _myField.Value
End Sub

When, e

3条回答
  •  甜味超标
    2020-12-19 11:43

    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 just means that the value will persist between calls.

    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 statics in c# are not instantiated in this way.


    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.

提交回复
热议问题