Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

もちろん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 には使えないけど、なんか他の利用方法ないかな~

tempura
フリーランスの天麩羅調理師 http://okamura0510.jp https://github.com/okamura0510 https://www.tempura.blog
http://okamura0510.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした