Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created November 29, 2012 14:55
Show Gist options
  • Select an option

  • Save ichiroku11/4169574 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/4169574 to your computer and use it in GitHub Desktop.
enumに適用されている属性を取得
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace ConsoleApp {
public static class EnumExtensions {
// enumに適用されている属性を取得
public static IEnumerable<TAttribute> GetApplied<TAttribute>(this Enum value) where TAttribute : Attribute {
return value
.GetType()
.GetField(value.ToString())
.GetCustomAttributes(false)
.OfType<TAttribute>();
}
}
enum Gender {
[Display(Name = "不明")]
Unknown,
[Display(Name = "男性")]
Male,
[Display(Name = "女性")]
Female,
}
class Program {
static void Main(string[] args) {
Console.WriteLine(Gender.Unknown.GetApplied<DisplayAttribute>().First().Name); // 不明
Console.WriteLine(Gender.Male.GetApplied<DisplayAttribute>().First().Name); // 男性
Console.WriteLine(Gender.Female.GetApplied<DisplayAttribute>().First().Name); // 女性
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment