我正在尝试制作一个通用函数,将枚举 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/