问题
I was reviewing the MSDN documentation on VB.Net's little-used Static keyword for local variables. My question is not about how Static works (I personally plan to avoid using it as it seems like it could cause grief to future programmers who don't notice the side-effects.) My question is about this statement in the docs:
The behavior of any local variable depends on whether it is declared in a Shared procedure. If the procedure is Shared, all its local variables are automatically shared. This includes the Static variables. There is only one copy of such a variable for the whole application.
This seems to imply that all local variables in a Shared Sub would behave like Static variables -- they would keep their values across separate calls. But I knew this wasn't the case, and I wrote a little test program to prove it:
Class TestSharedSub
Shared Sub Main()
Test()
Test()
Test()
Console.Write("Press any key to continue...") : Console.ReadKey()
' Output:
' 1, 1
' 2, 1
' 3, 1
End Sub
Shared Sub Test()
Dim iNormal As Integer
Static iStatic As Integer
iNormal += 1
iStatic += 1
Console.WriteLine(iStatic & ", " & iNormal)
End Sub
End Class
So can anyone interpret the above statement for me in a way that makes sense? Or is this a bug in the documentation? It's been there since the VS 2005 version of the docs and is still present in the Visual Studio 11 version.
回答1:
No, it's talking nonsense. It continues being utterly broken in the next paragraph:
If the procedure is not Shared, its local variables are instance variables.
Local variables aren't instance variables...
Whoever wrote that page appears not to understand local variables at all. Goodness knows what they'd make of recursion. Mind you, it starts off reasonably:
Normally, a local variable in a procedure ceases to exist as soon as the procedure stops.
... but that statement is clearly in contradiction to the later ones. Sigh.
I suggest you file a bug on Connect.
回答2:
That particular piece of documentation is wrong. Local variables declared in a Shared
method are no different than locals declared in a non-Shared method. The only behavior difference for locals comes into play with they are declared with the Static
modifier.
I'll alert the appropriate team about it.
EDIT
The team in charge of the documentation was alerted and will be correcting the documentation in the very near future.
来源:https://stackoverflow.com/questions/9689839/msdn-documentation-error-if-the-procedure-is-shared-all-its-local-variables-a