创建枚举列表并将其传递给一个方法

6
我创建了一个方法,它接收一个枚举类型并将其转换为一个字典,其中每个整数都与该枚举的名称(以字符串形式)相关联。
// Define like this
public static Dictionary<int, string> getDictionaryFromEnum<T>()
{
   List<T> commandList = Enum.GetValues(typeof(T)).Cast<T>().ToList();
   Dictionary<int, string> finalList = new Dictionary<int, string>();
   foreach (T command in commandList)
   {
    finalList.Add((int)(object)command, command.ToString());
   }
 return finalList;
 }

(注:是的,我有一个双重类型转换,但该应用程序旨在成为一种非常简单粗暴的C#枚举到Javascript枚举转换器。)

这样很容易使用:

private enum _myEnum1 { one = 1001, two = 1002 };
private enum _myEnum2 { one = 2001, two = 2002 };
// ... 
var a = getDictionaryFromEnum<_myEnum1>();
var b = getDictionaryFromEnum<_myEnum2>();

现在,我想知道是否可以创建一系列枚举列表来用于迭代我的调用。

这是原始问题中的内容:[为什么我不能调用它?]

我应该怎么做才能创建像这样的调用?

List<Type> enumsToConvertList = new List<Type>();
enumsToConvertList.Add(typeof(_myEnum1));
enumsToConvertList.Add(typeof(_myEnum2));
// this'll be a loop
var a = getDictionaryFromEnum<enumsToConvertList.ElementAt(0)>();

因为泛型中使用的类型与System.Type不同。 - antonijn
a的类型是什么? - svick
因为泛型仅支持静态类型。您正在尝试将类型对象放入通用方法中的类型参数。请尝试使用Type对象重写getDictionaryFromEnum。 - gabba
谢谢您的建议,对于烦扰我很抱歉。 - malber
5个回答

6

在运行时无法指定通用参数类型(除非使用反射)。因此,请创建一个非通用方法,该方法接受Type类型的参数:

public static Dictionary<int, string> getDictionaryFromEnum(Type enumType)
{
    return Enum.GetValues(enumType).Cast<object>()
               .ToDictionary(x => (int)x, x => x.ToString());
}

使用方法:

List<Type> enumsToConvertList = new List<Type>();
enumsToConvertList.Add(typeof(_myEnum1));
enumsToConvertList.Add(typeof(_myEnum2));

var a = getDictionaryFromEnum(enumsToConvertList[0]);

1
谢谢你的回答,懒人。我会接受你的答案,并从我的简历中删除“C#技能要求”的“高级知识”标签。 - malber
@malber 也许你只需要阅读几篇关于泛型和Linq的文章,而不是修改你的简历 :) - Sergey Berezovskiy

2
为什么我不能调用它?
在这种情况下,您正在传递 System.Type,它与通用类型指定不同,通用类型指定是编译时值。

1
这里有一种替代方法,它将枚举作为泛型并返回所有成员的字典。
 public static Dictionary<int, string> ToDictionary<T>()
    {
        var type = typeof (T);
        if (!type.IsEnum) throw new ArgumentException("Only Enum types allowed");
        return Enum.GetValues(type).Cast<Enum>().ToDictionary(value => (int) Enum.Parse(type, value.ToString()), value => value.ToString());
    }

0

稍后将其转换为指定类型:

List<Type> enumsToConvertList = new List<Type>();
enumsToConvertList.Add(_myEnum1);
var a = getDictionaryFromEnum<typeof(enumsToConvertList.ElementAt(0))>();

0
简单来说,泛型的类型参数必须在编译时已知。
您试图将运行时的 System.Type 对象作为泛型类型指示符进行传递,这是不可能的。
关于你想要实现的功能,你的方法实际上不需要是通用的,因为你总是返回一个 Dictionary<int, string>。尝试将 Type 作为参数传递给方法,就像 @lazyberezovsky 所演示的那样。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接