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

mal*_*ber 5 c# generics enums

我创建了一个方法,它接受枚举并在Dictionary中转换它,其中每个int与枚举的名称(作为字符串)相关联

// 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;
 }
Run Code Online (Sandbox Code Playgroud)

(ps.是的,我有一个双重演员,但该应用程序是一个非常便宜和肮脏的C#-enum到Javascript-enum转换器).

这可以很容易地使用

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

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

这是原来的问题:[为什么我不能称之为?]

我该怎么做才能创建像这样的电话?

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)>();
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 6

您不能在运行时指定泛型参数类型(嗯,没有反射).因此,只需创建非泛型方法,它接受Type类型的参数:

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

用法:

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

var a = getDictionaryFromEnum(enumsToConvertList[0]);
Run Code Online (Sandbox Code Playgroud)