Static variables in C#

前端 未结 5 561
梦如初夏
梦如初夏 2021-01-17 11:28

In C#, is there a way to put a static variable in a method like VB.Net?

Static myCollection As Collection
相关标签:
5条回答
  • 2021-01-17 11:47

    No, The CLR does not support this, and VB.NET resorts to compiler tricks to allow it. Ugh.

    0 讨论(0)
  • 2021-01-17 11:49

    No there isn't but how is this different then having a static variable at the class level?

    Actually if you look into how shared is implemented, it is a compiler trick that creates a static field on the class.

    0 讨论(0)
  • 2021-01-17 11:52

    I'm pretty sure the C# equivalent is const: therefore:

    public const Collection myCollection = new Collection();
    

    I'm not too familiar with VB.NET, so I could be off base, but that will allow you set a variable which cannot be changed.

    0 讨论(0)
  • 2021-01-17 12:01

    The closest thing to VB.NET's Static is to create a field in the current type. Other than that C# has no equivalent.

    0 讨论(0)
  • 2021-01-17 12:10

    Why doesn't C# support static method variables?

    Q: In C++, it's possible to write a static method variable, and have a variable that can only be accessed from inside the method. C# doesn't provide this feature. Why?

    A: There are two reasons C# doesn't have this feature.

    First, it is possible to get nearly the same effect by having a class-level static, and adding method statics would require increased complexity.

    Second, method level statics are somewhat notorious for causing problems when code is called repeatedly or from multiple threads, and since the definitions are in the methods, it's harder to find the definitions.

    -- msdn c# faq

    0 讨论(0)
提交回复
热议问题