【问题标题】:How to get all values of an enum?如何获取枚举的所有值?
【发布时间】:2009-04-29 05:46:01
【问题描述】:

我想创建一个接收Enum 类型的方法,并在一个数组中返回它的所有成员,如何创建这样的函数?

例如,我有这两个枚举:

public enum Family
{ 
   Brother,
   Sister,
   Father
}

public enum CarType
{ 
   Volkswagen,
   Ferrari,
   BMW
}

如何创建函数GetEnumList 使其返回

  1. {Family.Brother, Family.Sister, Family.Father} 第一种情况。
  2. {CarType.Volkswagen, CarType.Ferrari, CarType.BMW} 用于第二种情况。

我试过了:

private static List<T> GetEnumList<T>()
{
    var enumList = Enum.GetValues(typeof(T))
        .Cast<T>().ToList();
    return enumList;
}

但我有一个InvalidOperationException

System.InvalidOperationException:不能对 ContainsGenericParameters 为 true 的类型或方法执行后期绑定操作。 在 System.Reflection.RuntimeMethodInfo.ThrowNoInvokeException() 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object[] 参数,CultureInfo 文化,布尔型 skipVisibilityChecks) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object[] 参数,CultureInfo 文化) 在 System.Reflection.MethodBase.Invoke(Object obj, Object[] 参数)

编辑:上面的代码工作正常——我得到一个异常的原因是因为分析器给我带来了这个错误。谢谢大家的解决方案。

【问题讨论】:

  • 对我来说效果很好 - 你能发布调用代码吗?
  • 是的,它工作正常——我发现我的分析器实际上给我造成了一个错误,因此导致了异常。

标签: c# enums


【解决方案1】:

这里是完整的代码:

    public enum Family
    {
        Brother,
        Sister,
        Father
    }

    public enum CarType
    {
        Volkswagen,
        Ferrari,
        BMW
    }


    static void Main(string[] args)
    {
        Console.WriteLine(GetEnumList<Family>());
        Console.WriteLine(GetEnumList<Family>().First());
        Console.ReadKey();
    }

    private static List<T> GetEnumList<T>()
    {
        T[] array = (T[])Enum.GetValues(typeof(T));
        List<T> list = new List<T>(array);
        return list;
    }

【讨论】:

  • 以下有什么区别: (1)Enum.GetValues(typeof(theEnum)); // 返回 Enum (2)int i = (int) theEnum.item 中定义的纯枚举; // 如果未设置,则指标编号从零开始,如果设置了它们的值---- (3)Enum.GetNames (typeof (theEnum)); // 枚举名称以字符串形式返回
【解决方案2】:
(Family[])Enum.GetValues(typeof(Family))

【讨论】:

  • 谢谢,但我想要一个接受枚举类型并返回相应列表的通用方法——但需要一个特定的转换函数。
【解决方案3】:

与其他答案相同,但针对现代 C# 进行了更新:

public static List<TEnum> GetEnumList<TEnum>() where TEnum : Enum 
    => ((TEnum[])Enum.GetValues(typeof(TEnum))).ToList();

【讨论】:

    【解决方案4】:

    像这样?

    private static List<string> GetEnumList<T>()
    {
        return Enum.GetNames( typeof( T ) )
               .Select(s => typeof(T).Name + "." + s).ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-17
      • 2020-01-12
      • 2021-12-15
      • 2015-06-12
      • 2014-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 2011-04-18
      相关资源
      最近更新 更多