LoginSignup
10
9

More than 5 years have passed since last update.

C#でenumをクラスのように扱う

Last updated at Posted at 2015-10-14

もちろんenumはクラスではないので擬似的に、という感じだが。
方法としては拡張メソッドを使用する。

/// <summary>
/// ゲーム状態
/// </summary>
public enum GameState : int
{
    /// <summary>
    /// なにもなし
    /// </summary>
    None = 0,
    /// <summary>
    /// ゲーム開始
    /// </summary>
    Start = 1,
    /// <summary>
    /// ゲームプレイ中
    /// </summary>
    Play = 2,
    /// <summary>
    /// ゲーム終了
    /// </summary>
    Finish = 3,
}

public static class AppUtil
{
    /// <summary>
    /// ゲームプレイ中かどうか
    /// </summary>
    /// <param name="value">GameState</param>
    /// <returns>ゲームプレイ中なら true</returns>
    public static bool IsPlay(this GameState value)
    {
        return (value == GameState.Play);
    }

    /// <summary>
    /// 値取得
    /// </summary>
    /// <param name="value"></param>
    /// <returns>値</returns>
    public static int GetValue(this GameState value)
    {
        return (int)value;
    }
}

public class SceneStart : MonoBehaviour
{
    private static readonly string[] GameStateMes = { "なにもなし", "ゲーム開始", "ゲームプレイ中", "ゲーム終了" };

    void Main()
    {
        // ゲーム状態判定
        GameState state = GameState.Play;
        if (state.IsPlay())
        {
            // 値取得
            int value = state.GetValue();

            // メッセージ表示
            string mes = GameStateMes[value];
            Debug.Log(mes);
        }
    }
}

最初の発想は列挙型の名前が長くなってきた時に if 文の判定が長くなって1行で書けなくてスマートじゃなかったので、究極に短くするには?と考えた結果、上記のようにしてみた。ただ実際使ってみて enum の中身を拡張メソッドで隠ぺいしてるので分かりづらいは定義が長くなるわでデメリットの方が多く。。。そもそも enum にそんなたくさん情報持たせるなって話だけど(笑)

enum には使えないけど、なんか他の利用方法ないかな~

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9