Are global constants possible?

Is it possible to declare global constants? That is, constants available in all classes? When I try to declare a constant outside the class, as with the enumeration, I get a parsing error.

I have been using enums this way for a while, but enums are limited to integers, and I would like to use easy-to-use words instead of float values.

Example; I would like the following to be available in any class:

const float fast = 1.5f;
const float normal = 1f; 
const float slow = .75f;

I know I can get around this by creating enum (Speed) for speed names, and then creating a static SpeedNum () method that reads enum Speed ​​and returns the associated value, but it takes so much extra writing every time and I was hoping for something more elegant:

Example:

public double function SpeedNum(Speed speed) 
{
    switch (speed)
    {
        case speed.fast :
            return 1.5;
        case speed.normal :
            return 1f;
        case speed.slow :
            return .75f;
    }
+4
source share
3

, . 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;
  }
}

: .

+11

MSDN , :

const .

, , ,

, :

public static class GlobalConstant
{
    public const float fast = 1.5f;
    public const float normal = 1f; 
    public const float slow = .75f;
}

:

class MyProgram
{
    public static void Main()
    {
        Console.WriteLine(GlobalConstant.fast);
    }
}
+3

# 6 , "static_class_name.Thing", static, # 6.

// 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);
    }

}

. .

0
source

All Articles