C#中的静态变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/840397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:41:28  来源:igfitidea点击:

Static variables in C#

c#variablesstatic-variables

提问by norlando

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

在 C# 中,有没有办法将静态变量放在像 VB.Net 这样的方法中?

Static myCollection As Collection

采纳答案by chills42

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

为什么 C# 不支持静态方法变量?

问:在 C++ 中,可以编写一个静态方法变量,并且有一个只能从方法内部访问的变量。C# 不提供此功能。为什么?

A:C#没有这个特性有两个原因。

首先,通过类级静态可以获得几乎相同的效果,并且添加方法静态需要增加复杂性。

其次,当代码被重复调用或从多个线程调用时,方法级别的静态会导致问题而臭名昭著,并且由于定义在方法中,因此很难找到定义。

-- msdn c# 常见问题

回答by Andrew Hare

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

与 VB.NET 最接近的Static是在当前类型中创建一个字段。除此之外,C# 没有等价物。

回答by Otávio Décio

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

不,CLR 不支持这一点,VB.NET 求助于编译器技巧来允许它。啊。

回答by JoshBerke

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

不,没有,但这与在类级别拥有静态变量有何不同?

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

实际上,如果您查看shared 是如何实现的,它是一个在类上创建静态字段的编译器技巧。

回答by AllenG

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

我很确定 C# 等效项是const:因此:

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.

我对 VB.NET 不太熟悉,所以我可能不在基础上,但这将允许您设置一个无法更改的变量。