我尝试使用以下代码将枚举转换为通用列表
public static List<T> ToList<T>(Type t) where T : struct
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
Run Code Online (Sandbox Code Playgroud)
它顺利完成了.
我尝试使用以下代码调用上述方法
enum Fruit
{
apple = 1,
orange = 2,
banana = 3
};
private List<Fruit> GetFruitList()
{
List<Fruit> allFruits = EnumHelper.ToList(Fruit);
return allFruits;
}
Run Code Online (Sandbox Code Playgroud)
导致以下错误
Compiler Error Message: CS0118: 'default.Fruit' is a 'type' but is used like a 'variable'
Run Code Online (Sandbox Code Playgroud)
所以我确定如何将Enum类型作为参数传递.
public static List<T> ToList<T>() where T : struct
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
enum Fruit
{
apple = 1,
orange = 2,
banana = 3
};
private List<Fruit> GetFruitList()
{
List<Fruit> allFruits = EnumHelper.ToList<Fruit>();
return allFruits;
}
Run Code Online (Sandbox Code Playgroud)