【问题标题】:General method to convert enum to List<T> [duplicate]将枚举转换为 List<T> 的通用方法 [重复]
【发布时间】:2013-03-23 08:48:30
【问题描述】:

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

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

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;
   }
}

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

【问题讨论】:

  • 列表应该包含什么?
  • @Habib:我相信这不是重复的。因为用户可以将Enum1 或Enum2 作为参数传递。
  • @LasseV.Karlsen:如果可能,选择枚举的键和值。
  • 这是重复的,除非您的问题是“如何以流派方式或通过反射表达ExportEnumToList(&lt;enum choice&gt; enumName)>”。

标签: c#


【解决方案1】:
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>();

【讨论】:

  • +1:写泛型方法的好方法。
  • 其实这解决了我的问题。谢谢!
【解决方案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.
foreach (YourEnum item in Enum.GetValues(typeof(YourEnum ))){
    enumList.Add(item);
}
return enumList;    

}

【讨论】:

    猜你喜欢
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多