C#のEnumについて

2015年04月09日 (木) 23時02分15秒
このエントリーをはてなブックマークに追加

C#のEnumについて

Enumに対し行いたいことは、既にある

難易度の列挙型を定義しよう

public enum Difficulty { Easy, Normal, Hard };

for文で回したい

for(var i=0;i<(int)Difficulty.Hard+1;i++)

Extremeなんてのを追加した

public enum Difficulty { Easy, Normal, Hard, Extreme };

先ほどのfor文は

for(var i=0;i<(int)Difficulty.Extreme+1;i++)

に変更する

列挙型に変更がある度にfor文まで変更するのは良くない

public enum Difficulty { Easy, Normal, Hard, Extreme, MAX };
for(var i=0;i<(int)Difficulty.MAX;i++)

MAXは便宜上つけただけで実際には使われない

ここでC#のEnumについて(using System)
値を列挙

Enum.GetValues(typeof(Difficulty))

名前を列挙

Enum.GetNames(typeof(Difficulty))

サイズを取得

Enum.GetNames(typeof(Difficulty)).Length

forで回す

for(var i=0;i<Enum.GetNames(typeof(Difficulty)).Length;i++)

foreachで回す

foreach(string str in Enum.GetValues(typeof(Difficulty)))

Difficulty型diffをstring型にする

string str=diff.ToString();

string型strをDifficulty型にする

Difficulty diff=(Difficulty)Enum.Parse(typeof(Difficulty), str);

もしstrに一致する値がなかったら?
例外がスローされる

例外処理を入れずに一致するか見たい

if (Enum.IsDefined(typeof(Difficulty), str))

一致する場合のみ変換するTryParseなんてのもあるらしい

参考
http://qiita.com/hugo-sb/items/38fe86a09e8e0865d471
http://www.atmarkit.co.jp/fdotnet/csharp_abc/csharp_abc_016/csharp_abc01.html
http://dobon.net/vb/dotnet/programing/enumgetvalues.html