Visual C# 中的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1806387/
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-06 21:00:48  来源:igfitidea点击:

Global variables in Visual C#

c#visual-studioglobal-variables

提问by neuromancer

How do I declare global variables in Visual C#?

如何在 Visual C# 中声明全局变量?

采纳答案by Bob

How about this

这个怎么样

public static class Globals {
    public static int GlobalInt { get; set; }
}

Just be aware this isn't thread safe. Access like Globals.GlobalInt

请注意这不是线程安全的。访问喜欢Globals.GlobalInt

This is probably another discussion, but in general globals aren't really needed in traditional OO development. I would take a step back and look at why you think you need a global variable. There might be a better design.

这可能是另一个讨论,但一般来说,传统 OO 开发中并不真正需要全局变量。我会退后一步,看看为什么你认为你需要一个全局变量。可能会有更好的设计。

回答by Russell

Use the const keyword:

使用 const 关键字:

public const int MAXIMUM_CACHE_SIZE = 100;

Put it in a static class eg

把它放在一个静态类中,例如

public class Globals
{
    public const int MAXIMUM_CACHE_SIZE = 100;
}

And you have a global variable class :)

而且你有一个全局变量类:)

回答by Mark Bertenshaw

The nearest you can do this in C# is to declare a public variable in a public static class. But even then, you have to ensure the namespace is imported, and you specify the class name when using it.

在 C# 中最接近的方法是在公共静态类中声明一个公共变量。但即便如此,您也必须确保导入命名空间,并在使用时指定类名。

回答by JohannesH

A public static field is probably the closest you will get to a global variable

公共静态字段可能是最接近全局变量的字段

public static class Globals
{
  public static int MyGlobalVar = 42;
}

However, you should try to avoid using global variables as much as possible as it will complicate your program and make things like automated testing harder to achieve.

但是,您应该尽量避免使用全局变量,因为它会使您的程序复杂化并使诸如自动化测试之类的事情更难以实现。