LoginSignup
21
21

More than 5 years have passed since last update.

属性に設定したenumの値に対応する文字列を取得する。

Posted at

画面に表示するときなどenumの値をそのままではなく、(もっと人間判りやすいように)値に対応する文字列を表示したいということは良くあって、以前、enumに拡張メソッドを定義すればスッキリ書けるんじゃないかということを書きました(C# の enum に関連する小技。)。

この方法は単純で良いと思うんですが、enumの定義と対応する名称の定義の場所が離れてるのが何か格好悪い。
そこで、属性を使えばもっと綺麗に書けるんじゃないかと試してみました。

拡張メソッドの中身がややこしくなりましたが、ジェネリックにして使いまわしできるようにすれば良いかな。

enumTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace EnumTest
{
    // enum 定義
    enum Gender
    {
        [Display(Name = "不明")]
        Unknown,
        [Display(Name = "男性")]
        Male,
        [Display(Name = "女性")]
        Female
    }

    // Genderに対する拡張メソッドを定義する
    static class GenderExt {
        // 表示名を取得する。
        public static string DisplayName(this Gender value) {
            var fieldInfo = value.GetType().GetField(value.ToString());
            var descriptionAttributes = fieldInfo.GetCustomAttributes(
                typeof(DisplayAttribute), false) as DisplayAttribute[];
            if (descriptionAttributes != null && descriptionAttributes.Length > 0) {
                return descriptionAttributes[0].Name;
            } else {
                return value.ToString();
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            foreach (var e in Enum.GetValues(typeof(Gender)) as IEnumerable<Gender>)
            {
                Console.Out.WriteLine(e.DisplayName());
            }
            Console.In.ReadLine();
        }
    }
}
21
21
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
21
21