Last active
December 11, 2015 21:29
-
-
Save kawakawa/4663026 to your computer and use it in GitHub Desktop.
euumに設定してあるDescription属性を取得する方法
This file contains 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.Linq; | |
using System.Text; | |
using System.ComponentModel; | |
using System.Reflection; | |
namespace EnumDescriptionSample | |
{ | |
class Program | |
{ | |
enum Signal : int | |
{ | |
[Description("赤信号")] | |
RED = 1, | |
[Description("黄信号")] | |
YELLOW = 2, | |
//[Description("青信号")] | |
BULE = 3 | |
} | |
private string GetEnumDescription(Signal value) | |
{ | |
FieldInfo fi = value.GetType().GetField(value.ToString()); | |
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); | |
var desciptionString = attributes.Select(n=>n.Description) | |
.FirstOrDefault(); | |
if (desciptionString != null) | |
{ | |
return desciptionString; | |
} | |
return value.ToString(); | |
} | |
static void Main(string[] args) | |
{ | |
var signal = new Program(); | |
Console.WriteLine(signal.GetEnumDescription(Signal.RED)); | |
Console.WriteLine(signal.GetEnumDescription(Signal.YELLOW)); | |
Console.WriteLine(signal.GetEnumDescription(Signal.BULE)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment