Created
November 29, 2012 14:55
-
-
Save ichiroku11/4169574 to your computer and use it in GitHub Desktop.
enumに適用されている属性を取得
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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