列挙体の説明を取得する
列挙体を何か分かりやすい文字列で表示したいときとか、
属性で[Description]付けておいて、表示する時に変換して使ったりする。
1 [TestFixture]
2 public class EnumTest
3 {
4 enum PersonType
5 {
6 [Description("俺")] me = 0,
7 [Description("あんた")] you,
8 [Description("他人")] other,
9 }
10
11 private string GetDescription( Enum value )
12 {
13 FieldInfo fi = value.GetType().GetField( value.ToString() );
14 DescriptionAttribute attributes =
15 (DescriptionAttribute)fi.GetCustomAttributes( typeof(DescriptionAttribute),false );
16 return (attributes.Length > 0)?attributes[0].Description:value.ToString();
17 }
18
19 [Test]
20 public void Test_Description()
21 {
22 PersonType pType = PersonType.me;
23 string name = GetDescription( pType );
24 Assert.AreEqual(name,"俺");
25 }
26 }