如何在 C# 中使用全局变量? [英] How to use Global Variables in C#?

查看:41
本文介绍了如何在 C# 中使用全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

C# 中,您不能定义真正的全局变量(因为它们不属于任何类).

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

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

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

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):

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

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

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

  • 声明Globals 类,但不将其包含在特定的命名空间 中(以便将其放置在全局应用程序命名空间中);
  • 插入正确的 using 指令以从另一个 namespace 检索变量.
  • declare the Globals class 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.

这篇关于如何在 C# 中使用全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆