【C#】列挙型の項目数取得
例えば、こんな感じな列挙型を定義する
enum Direct { Up, Down, Left, Right }
項目数取得
// enum => string[] => 文字列数取得 Enum.GetNames(typeof(Direct)).Length;
テンプレートで実装する
public static class EnumExtension { public static int Length<T>() { var type = typeof(T); if(!type.IsEnum) throw new Exception("T is not enum!!"); return Enum.GetNames(type).Length; } }
こんな感じ使う
EnumExtension.Length<Direct>();