5

这是一个“奇怪”的问题:

是否可以创建一个方法,其中将任何枚举转换为列表。这是我目前正在考虑的草稿。

public class EnumTypes
{
   public enum Enum1
   {
      Enum1_Choice1 = 1,
      Enum1_Choice2 = 2
   }

   public enum Enum2
   {
      Enum2_Choice1 = 1,
      Enum2_Choice2 = 2
   }

   public List<string> ExportEnumToList(<enum choice> enumName)
   {
      List<string> enumList = new List<string>();
      //TODO: Do something here which I don't know how to do it.
      return enumList;
   }
}

只是好奇它是否可能以及如何做到这一点。

4

2 回答 2

11
Enum.GetNames( typeof(EnumType) ).ToList()

http://msdn.microsoft.com/en-us/library/system.enum.getnames.aspx

或者,如果你想变得花哨:

    public static List<string> GetEnumList<T>()
    {
        // validate that T is in fact an enum
        if (!typeof(T).IsEnum)
        {
            throw new InvalidOperationException();
        }

        return Enum.GetNames(typeof(T)).ToList();
    }

    // usage:
    var list = GetEnumList<EnumType>();
于 2013-04-02T06:38:36.537 回答
0
public List<string> ExportEnumToList(<enum choice> enumName)    {
List<string> enumList = new List<string>();
//TODO: Do something here which I don't know how to do it.
foreach (YourEnum item in Enum.GetValues(typeof(YourEnum ))){
    enumList.Add(item);
}
return enumList;    

}

于 2013-04-02T06:39:00.077 回答