如何在 C# 中使用全局变量?

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

How to use Global Variables in C#?

c#variablesscope

提问by Mas Ajum

How do I declare a variable so that every class (*.cs) can access its content, without an instance reference?

如何声明一个变量,以便每个类 (*.cs) 都可以访问其内容,而无需实例引用?

回答by Federico Berasategui

There's no such thing as a global variable in C#. Period.

C# 中没有全局变量这样的东西。时期。

You can have static members if you want:

如果需要,您可以拥有静态成员:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

回答by Tommaso Belluzzo

In C#you cannot define true global variables (in the sense that they don't belong to any class).

C#您不能定义真正的全局变量(从某种意义上说,它们不属于任何类)。

This being said, the simplest approach that I know to mimic this feature consists in using a static class, as follows:

话虽如此,我所知道的模仿此功能的最简单方法是使用 a static class,如下所示:

public static class Globals
{
    public const Int32 BUFFER_SIZE = 512; // Unmodifiable
    public static String FILE_NAME = "Output.txt"; // Modifiable
    public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}

You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace):

然后,您可以在代码中的任何位置检索定义的值(前提是它是相同的一部分namespace):

String code = Globals.CODE_PREFIX + value.ToString();

In order to deal with different namespaces, you can either:

为了处理不同的命名空间,您可以:

  • declare the Globalsclass without including it into a specific namespace(so that it will be placed in the global application namespace);
  • insert the proper using directive for retrieving the variables from another namespace.
  • 声明Globals类而不将其包含到特定的中namespace(以便将其放置在全局应用程序命名空间中);
  • 插入正确的 using 指令以从另一个namespace.

回答by DeepSpace101

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.

首先检查您是否真的需要一个全局变量而不是公然使用它而不考虑您的软件架构。

Let's assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other "bad things", it's best to approach them from an angle where you're prepared to handle such bad things. So,

让我们假设它通过了测试。根据使用情况,全局变量可能很难在竞争条件和许多其他“坏事”下进行调试,最好从您准备好处理这些坏事的角度来处理它们。所以,

  1. Wrap all such Global variables into a single staticclass (for manageability).
  2. Have Properties instead of fields(='variables'). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.
  1. 将所有此类全局变量包装到一个static类中(为了便于管理)。
  2. 有属性而不是字段(=‘变量’)。这样,您就有了一些机制来解决将来并发写入 Globals 的任何问题。

The basic outline for such a class would be:

这样一个类的基本大纲是:

public class Globals
{
    private static bool _expired;
    public static bool Expired 
    {
        get
        {
            // Reads are usually simple
            return _expired;
        }
        set
        {
            // You can add logic here for race conditions,
            // or other measurements
            _expired = value;
        }
    }
    // Perhaps extend this to have Read-Modify-Write static methods
    // for data integrity during concurrency? Situational.
}

Usage from other classes (within same namespace)

其他类的使用(在同一命名空间内)

// Read
bool areWeAlive = Globals.Expired;

// Write
// past deadline
Globals.Expired = true;

回答by Zotta

A useful feature for this is using static

一个有用的功能是 using static

As others have said, you have to create a class for your globals:

正如其他人所说,您必须为全局变量创建一个类:

public static class Globals {
    public const float PI = 3.14;
}

But you can import it like this in order to no longer write the class name in front of its static properties:

但是你可以像这样导入它,以便不再在它的静态属性前面写类名:

using static Globals;
[...]
Console.WriteLine("Pi is " + PI);