After a long time to learn vb.net local static variables, so share with you, read this article you certainly have a lot of harvest, hope this article can teach you more things. Vb. NET can achieve many functions that C # cannot do, such as when statement, optional parameter, local static variable, object instance access static method, handles binding event, on error handling exception, Object direct late binding, etc. VB and C # belong together. NET language, the same CIL is compiled, but why does VB support a lot of interesting features? Let's explore the vb.net local static variables.
Vb. NET local static variables
VB supports declaring local variables with the static keyword so that the value of the variable can be persisted at the end of the process:
Public Sub Test1 () Static I as Integer i + + 1 implements a procedure call counter end Sub
We have implemented a simple process counter. Each time you call test, the counter's value increases by 1. There are many situations where we want to keep the values of the variables. The static of C # cannot be used within the process. So to implement the process counter, we have to declare a class-level variable. This is obviously not as good as VB. Because it is not possible to prevent other procedures from modifying counter variables. This is the same thing as the object encapsulation, which should have been a local variable of a method, and now I am forced to separate it out, obviously a bad design. So how does VB generate local static variables? We can clearly see in the VB generated CIL that I was not a local variable, but rather as a field of the class:
. field Private specialname int32 $STATIC $test1$2001$i
In other words, I was renamed as a class field, but was dubbed SpecialName. Attempting to access $static$test1$2001$i in code is not possible because it is not a valid identifier. But in IL, the code that adds this variable to one is exactly the same as the generic class field, and is loaded by ldfld. I think this method is very clever, the static variable into the life cycle of the same class field, but also by the compiler to control access to the permissions, let it become a local variable. It also explains why VB uses two different keywords to declare static variables--static and shared.
Because the essence of the vb.net local static variable is the field of the class, it differs from the real local variable. For example, in multi-threaded conditions, the access to vb.net local static variables is the same as the Access field.