全局常数是否可能?

gre*_*ace 8 c#

是否可以声明全局常量?也就是说,所有类中都有常量?当我尝试在类之外声明一个常量时,就像我对枚举一​​样,我得到一个解析错误.

我一直用这种方式使用枚举,但枚举仅限于整数,我想使用易于使用的单词而不是浮点值.

例; 我想在任何课程中都可以使用以下内容:

const float fast   = 1.5f;
const float normal = 1f; 
const float slow   = .75f;
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过为速度名称创建一个枚举(速度)来解决这个问题,然后创建一个静态方法SpeedNum()来读取枚举Speedreturn一个相关的值,但每次都需要这么多额外的写法,我希望有更优雅的东西:

例如:

public double function SpeedNum(Speed speed) 
{
    switch (speed)
    {
        case speed.fast:   return 1.5;
        case speed.normal: return 1f;
        case speed.slow:   return .75f;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*kus 22

创建一个静态类,例如Constants包含常量并使用它来访问它们Constants.MyConstant.

public static class Constants
{
  public const string MyConstant = "Hello world";
  public const int TheAnswer = 42;
}

class Foo
{
  // ...

  private string DoStuff()
  {
    return Constants.MyConstant;
  }
}
Run Code Online (Sandbox Code Playgroud)

回答你的隐含问题:你不能在类之外声明常量.


Nig*_*vel 5

如果您的目标是C#版本6或更高版本,并且不想使用传统的“ static_class_name.Thing”,则可以使用C#6中引入的static

// File 1
public static class Globals
{
    public const string bobsName = "bob!";
}

// File 2
using System;
using static Globals;

class BobFinder
{
    void Run() => Console.WriteLine(bobsName);
}
Run Code Online (Sandbox Code Playgroud)

语法糖。但是我觉得这很漂亮。

  • 从 C# 10 开始,你可以在某个地方有一个 `global using static Globals;`,而不是在每个文件中都需要它..(PS 我会大写 `bobsName`) (2认同)