是否有一种方法将枚举转换为包含所有枚举选项的列表?


当前回答

这将返回一个枚举的所有值的IEnumerable<SomeEnum>。

Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();

如果你希望它是一个List<SomeEnum>,只需在. cast <SomeEnum>()之后添加. tolist()。

要在数组上使用Cast函数,您需要拥有System。Linq在你的使用部分。

其他回答

非常简单的答案

下面是我在一个应用程序中使用的属性

public List<string> OperationModes
{
    get
    {
       return Enum.GetNames(typeof(SomeENUM)).ToList();
    }
}

这将返回一个枚举的所有值的IEnumerable<SomeEnum>。

Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();

如果你希望它是一个List<SomeEnum>,只需在. cast <SomeEnum>()之后添加. tolist()。

要在数组上使用Cast函数,您需要拥有System。Linq在你的使用部分。

你可以使用下面的泛型方法:

public static List<T> GetItemsList<T>(this int enums) where T : struct, IConvertible
{
    if (!typeof (T).IsEnum)
    {
        throw new Exception("Type given must be an Enum");
    }

    return (from int item in Enum.GetValues(typeof (T))
            where (enums & item) == item
            select (T) Enum.Parse(typeof (T), item.ToString(new CultureInfo("en")))).ToList();
}
Language[] result = (Language[])Enum.GetValues(typeof(Language))
/// <summary>
/// Method return a read-only collection of the names of the constants in specified enum
/// </summary>
/// <returns></returns>
public static ReadOnlyCollection<string> GetNames()
{
    return Enum.GetNames(typeof(T)).Cast<string>().ToList().AsReadOnly();   
}

其中T是枚举类型; 添加:

using System.Collections.ObjectModel;