如何使用枚举作为键来创建一个const数组的字符串?

时间:2017-11-26 00:34:17

标签: c# enums

以下是我在CSharp中要做的事情,但我不知道该怎么做(我知道这是无效的C# ):

const enum GameOver { Winner, Looser, Tied, };
GameOvers = [
    GameOver.Winner: "Person is the winner",
    GameOver.Looser: "Person is the looser",
    GameOver.Tied: "Game is tied",
]

之后,我希望能够称之为:

Display(GameOvers[GameOver.Winner])

(我想实际处理这样的const数组错误。)

你会如何做到C#

2 个答案:

答案 0 :(得分:1)

我想到的最接近的方法是使用Dictionary<GameOver, string>

enum GameOver { Winner, Loser, Tied };

Dictionary<GameOver, string> GameOvers =  new Dictionary<GameOver, string>()
{
    {GameOver.Winner, "Person is the winner"}, 
    {GameOver.Loser,  "Person is the loser"},
    {GameOver.Tied,   "Game is tied"}
};

但请注意,您不能使Dictionary真正保持不变,因为该实例是可变的。

答案 1 :(得分:-1)

public static readonly String[] Messages =
{
    "Person is the winner",
    "Person is the looser",
    "Game is tied"
};

public enum GameOver
{
    Winner = 0,
    Looser = 1,
    Tied = 2
}

Display(Messages[(Int32)GameOver.Winner]);

可能不那么紧凑但功能齐全。由于readonly属性(What are the benefits to marking a field as `readonly` in C#?),您的字符串也将被保证为不可变。