如何在 C# 中存储有组织的常量列表

Zor*_*gan 1 c# unity-game-engine

我想存储每个游戏级别的固定设置。我希望它的结构如下:

namespace LevelSettings
{
    namespace Bar
    {
        public static int ExtraActiveBlocks = 3;

        "Level1"
        {   public static float Speed = 0.6f;
            public static string ActiveColor = "red";
            public static string InactiveColor = "black";
        },
        "Level2"
        {
            public static float Speed = 0.6f;
            public static string ActiveColor = "red";
            public static string InactiveColor = "black";
        },
        "Level3"
        {
            public static float Speed = 0.6f;
            public static string ActiveColor = "red";
            public static string InactiveColor = "black";
        }
Run Code Online (Sandbox Code Playgroud)

这显然不是有效的 C# 代码。不过我想问如何用 C# 编写它。

因此,在我的 C# (Unity) 脚本中,我想访问如下字段:

str currentLevel = "Level1"
float currentSpeed = LevelSettings.Bar.{currentLevel}.Speed;
Run Code Online (Sandbox Code Playgroud)

这个存储和访问功能可以用 C# 实现吗?如果是的话,上面的事情该怎么办呢?

Jam*_*iec 5

常量内有一个静态字典,其中键是级别,值是代表 3 个属性的对象。

namespace LevelSettings
{
    public class LevelSetting
    {
       public float Speed {get;}
       public string ActiveColor{get;}
       public string InactiveColor{get;}
    
       public LevelSetting(float speed, string activeColor, string inactiveColor)
       {
           /// set the properties, omitted for brevity
       }
    }

    class Bar
    {
        public static int ExtraActiveBlocks = 3;
        public static IReadOnlyDictionary<string,LevelSetting> Levels = new Dictionary<string,LevelSetting>()
        {
           ["Level1"] = new LevelSetting(0.6f, "red","black"),
           ["Level2"] = new LevelSetting(0.6f, "red","black"),
           ["Level3"] = new LevelSetting(0.6f, "red","black")
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以做

string currentLevel = "Level1"
float currentSpeed = LevelSettings.Bar.Levels[currentLevel].Speed;
Run Code Online (Sandbox Code Playgroud)