44
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Enumメモ

Posted at

目的

最近Java、C#、その他言語でのコーディングが同時進行で頭がぼーんしそうなので
よく使う書き方をメモ。

とりあえず適当なenumを作成

enum Disney 
{
    MICKEY = 1,
    MINNIE = 2,
    GOOFY = 3,
    DONALD = 4
}

名前を取得

Enum.GetName(typeof(Disney), Disney.MICKEY);

値を取得

(int)Disney.MICKEY

値からEnumを取得

int disneyValue = 1;

//キャスト
Disney disney = (Disney)disneyValue;
//Enum.ToObject
Disney disney2 = (Disney)Enum.ToObject(typeof(Disney), disneyValue);

ループ

foreach (Disney disney in Enum.GetValues(typeof(Disney)))
{
    //繰り返し処理
}

型指定

//byte、sbyte、short、ushort、int、uint、long、ulongのいずれかが指定可能
enum Disney : int
{
    MICKEY = 1,
    MINNIE = 2,
    GOOFY = 3,
    DONALD = 4
}

拡張メソッド

もう少し便利に使いたかったら拡張メソッドを実装すればいい。

using System;
namespace EnumSample
{
    enum Disney
    {
        MICKEY = 1,
        MINNIE = 2,
        GOOFY = 3,
        DONALD = 4
    }
    static class DisneyExtension
    {
        /// <summary>
        /// Nameを返します。
        /// <summary>
        public static string GetName(this Disney disney)
        {
            return Enum.GetName(typeof(Disney), disney);
        }

        /// <summary>
        /// Valueを返します。
        /// </summary>
        public static int GetValue(this Disney disney)
        {
            return (int)disney;
        }
    }
}
44
43
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
44
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?