기본카테고리

[C#]enum에 String을 사용하는 예제

DevReff 2016. 10. 21. 16:03
728x90
SMALL

=================================================================================
 public class StringValue : System.Attribute
 {
  private string _value;

  public StringValue(string value)
  {
   _value = value;
  }

  public string Value
  {
   get { return _value; }
  }
 }

 public class StringEnum
 {
  /// <summary>
  /// enum에 String 사용시 enum 상수의 문자열값을 구한다.
  /// </summary>
  /// <typeparam name="T">임의의 enum형</typeparam>
  /// <param name="value">임의의 enum형 변수</param>
  /// <returns>enum 상수의 문자열값</returns>
  public static string GetStringValue<T>(T value)
  {
   string output = "";

   Type type = value.GetType();

   FieldInfo fi = type.GetField(value.ToString());
   StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[];

   if (attrs.Length > 0)
   {
    output = attrs[0].Value;
   }

   return output;

  }

 

=================================================================================
 /// <summary>
 /// ID
 /// </summary>
 public enum TestID
 {
  Foundation = 1,
  Unknown = 0xFF
 }

 

 public enum TestName
 {
  [StringValue("기초")]
  Foundation = TestID.Foundation,
  [StringValue("알수없슴")]
  Unknown = TestID.Unknown,
 }

 

 public class TestUtil
 {
  #region Member variable
  static public string Foundation
  {
   get { return StringEnum.GetStringValue(Enum.Parse(typeof(TestName), TestID.Foundation.ToString())); }
  }
  static public string Unknown
  {
   get { return StringEnum.GetStringValue(Enum.Parse(typeof(TestName), TestID.Unknown.ToString())); }
  }
  #endregion

 

  static public List<string> Names()
  {
   List<string> results = new List<string>();
   foreach (TestName value in Enum.GetValues(typeof(TestName)))
    results.Add(StringEnum.GetStringValue(Enum.Parse(typeof(TestName), value.ToString())));

   return results;
  }
  static public List<TestID> IDs()
  {
   List<TestID> results = new List<TestID>();
   foreach (TestID value in Enum.GetValues(typeof(TestID)))
    results.Add(value);

   return results;
  }
  static public string Name(TestIDid)
  {
   return StringEnum.GetStringValue(Enum.Parse(typeof(TestName), id.ToString()));
  }
  static public TestIDID(TestName name)
  {
   return (TestID)Enum.Parse(typeof(TestID), name.ToString());
  }
  static public TestID ID(string name)
  {
   return (TestID)Enum.Parse(typeof(TestID), name);
  }
 }