c# - 尝试在 C# 中将枚举 system.array 转换为枚举 List<T>

标签 c# list enums

我正在尝试制作一个通用函数,将枚举 System.Array 转换为这些枚举的列表,但我不知道枚举数组的类型。我尝试了几种方法,但无法使其正常工作。应该是这样的……谢谢

    public static List<T> SArrayEnumToList<T>(System.Array arr){
        Type enumType = typeof(T);

        if(enumType.BaseType != typeof(Enum))
            throw new ArgumentException("T must be of type System.Enum");

        List<T> enumList = new List<T>(new T[arr.Length]);
        int i;
        for(i=0;i<arr.Length;i++) {
            enumList.Add(( T )Enum.Parse(enumType, arr.GetValue(i).ToString()));
        }

        return enumList;
    }

最佳答案

你真的只需要使用 Linq ToList()方法:

var myEnumsList = myEnumsArray.ToList();

文档指出 ToList() 返回一个列表“包含来自输​​入序列的元素”。

如果你真的想把这个功能分解成你自己的方法,你可以这样做:

private static List<T> ToList<T>(T[] enums) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new ArgumentException("T must be an enum.");
    }
    return enums.ToList();
}

Constraining type of generic type T 限制调用方法时可以使用的类型。 Enum 是一个 struct 并实现 IConvertible,如 here 中所述。 .

编辑:

因为您确实需要使用 System.Array。迭代 System.Array,将每个值转换为通用类型 T 并在返回前添加到列表中。 工作示例:

public static List<T> ToList<T>(Array array) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new ArgumentException("T must be an enum.");
    }
    List<T> enumValues = new List<T>();
    foreach (var enumValue in array)
    {
        enumValues.Add((T)enumValue);
    }
    return enumValues;
}

编辑#2 评论后更新。

public static IList ToList(Array array)
{
    Type elementType = array.GetType().GetElementType();
    Type listType = typeof(List<>).MakeGenericType(new[] { elementType });
    IList list = (IList)Activator.CreateInstance(listType);
    foreach (var enumValue in array)
    {
        list.Add(enumValue);
    }
    return list;
}

关于c# - 尝试在 C# 中将枚举 system.array 转换为枚举 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52697952/

相关文章:

java - 如何按枚举的顺序对 List<Enum, Collection> 进行排序?

Python - 在列表中搜索多个值并执行多个操作

java - 用字符串填充 Double 列表

c# - 无法在循环中修改结构的对象

c# - Windows服务安装过程中的问题

python - 在 Python 2 中搜索字典

c++ - 未命名类型错误是由于现有枚举造成的,但为什么呢?

vba - 有没有办法在VBA中将算术和逻辑运算符作为方法参数传递?

c# - 如何在 Mono 和 Visual Studio 2010(C#4.0) 上跳过延迟签名程序集的强名称验证?

c# - Expression_Host 程序集的数量不断增长