我发现计算器这个答案枚举某一类型的枚举:如何在枚举类型仅在运行时知道枚举枚举?
var values = (SomeType[])Enum.GetValues(typeof(SomeType));
,如果我硬代码枚举类型完美的作品。但我需要能够在运行时设置类型。我尝试以下,但这不起作用:
var values = (typeof(T)[])Enum.GetValues(typeof(T));
我发现计算器这个答案枚举某一类型的枚举:如何在枚举类型仅在运行时知道枚举枚举?
var values = (SomeType[])Enum.GetValues(typeof(SomeType));
,如果我硬代码枚举类型完美的作品。但我需要能够在运行时设置类型。我尝试以下,但这不起作用:
var values = (typeof(T)[])Enum.GetValues(typeof(T));
你T
已经Type
型。没有必要使用另一个typeof
。一个简单的强制转换为T[]
应该足够了:
T[] values = (T[]) Enum.GetValues(typeof(T));
typeof(T)
通常会返回你Type
对象,所以编译器认为要应用索引到该对象。
尝试使用:
Enum.GetValues(typeof(T)).Cast<T>()
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
您可以使用结果custing的Cast<T>()
方法和类型检查typeof(T).IsEnum
方法(T
必须是一个枚举类型)。
目标方法:
public static IEnumerable<T> GetValues<T>()
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
return Enum.GetValues(typeof(T)).Cast<T>();
}
用例:
public enum EnumFoo
{
Foo1, Foo2
}
public enum EnumBar
{
Bar1, Bar2
}
public void Main()
{
foreach (var value in GetValues<EnumFoo>())
Console.WriteLine(value); // Foo1 Foo2
foreach (var value in GetValues<EnumBar>())
Console.WriteLine(value); // Bar1 Bar2
}
你的意思是,你需要在运行时设置呢? – 2014-11-23 15:56:25
您的意思是:不起作用?它不会编译或者在运行时显示错误(以及错误)? – Sjips 2014-11-23 15:59:06
“我在stackoverflow上找到了这个答案” - 为了提供信用,总是建议将相应的文本转换为*链接*到您提到的答案。 – 2014-11-23 15:59:22