2017-11-26 10 views
0

は、ここで私はCSHARPでやってみたいものだが、私は(私はこれがC#有効ではありません知っているを)これを行う方法を知らない:enumをキーとして文字列のconst配列を作る方法は?

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#でどうやったらいいですか?インスタンスが変更可能であるので、あなたは、Dictionaryが実際に一定にすることができないこと、

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"} 
}; 

しかし予告:

+0

[説明]属性または[これと類似のもの](https://stackoverflow.com/q/424366/1070452)を使用できますか? – Plutonix

+0

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer –

+0

この質問は、あなたが必要とするものを持っています:https://stackoverflow.com/questions/479410/enum-tostring-with-user-friendly-strings –

答えて

0

私の心に入ってくる最接近はDictionary<GameOver, string>を使用しています。

+0

これは*まさにあなたが答えた直前のことです** '; ^)' * *おかげさまで、ありがとうございました! –

-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#?)のおかげで、文字列も不変であることが保証されます。

+2

忍者downvoteの理由は? –

+0

文字列は常に不変です。しかし、配列はそうではありません。 readonlyキーワードは、変数 '' Messages''を指す配列ではなく、読み込み専用にします。 – dumetrulo

+0

私は間違った方法でそれを説明しますが、コードの背後にあるコンセプトはちょっと明白です。 –

関連する問題