Why doesn't C# have local static variables like C? I miss that!!
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
I think the idea of local statics is just as easily solved by creating public static fields to the class. Very little logical change don't you think?
If you think it would be a big logical change, I'd be interested to hear how.
If you can imagine some sort of Lippert/Farnsworth hybrid entity announcing GOOD NEWS EVERYONE!, C# 6.0 allows the
using static
statement. This effectively allows you to import static class methods (and, it seems, properties and members as well) into the global scope.In short, you can do something like this:
While this is only available in C# 6.0, from what I understand the generated assemblies should be compatible with previous .NET platforms (correct me if I'm wrong).
The MSDN blog entry Why doesn't C# support static method variables? deals with the exact question asked in the original post:
Because static local variables are tied to the method, and the method is shared amongst all instances.
I've had to correct myself and other programmers who expect it to be unique per class instance using the method.
However, if you make it a static class, or static instance of a class, it's syntactically clear whether there's an instance per container-class, or one instance at all.
If you don't use these, it becomes easier to refactor later as well.
State is generally part of an object or part of a type, not part of a method. (The exception being captured variables, of course.)
If you want the equivalent of a local static variable, either create an instance variable or a static variable - and consider whether the method itself should actually be part of a different type with that state.
You can use nested-class as a workaround for this. Since C# is limiting the scope of static variables to classes, you can use nested-class as a scope.
For example:
Here
Foo
supportsIncrement
method, but its support it by the private nested classIncrementInternal
which contains the static variable as a member. And of course,counter
is not visible in the context (other methods) ofFoo
.BTW, if you want to access to
Foo
context (other members and methods) insideIncrementInternal.Increment
, you can passthis
as a parameter toIncrementInternal.Increment
when you call it fromFoo
.To keep the scope as small as possible, I'm suggesting to create a nested class per each such method. And because it is probably not so common, the number of nested classes will stay small enough to maintains it.
I think it is cleaner than anonymous functions or IIFE.
You can see a live demo here.