[英]How to enumerate enums when the enum type is only known at runtime?
I found this answer on stackoverflow to enumerate an enum of a certain type: 我在stackoverflow上找到了这个答案来枚举某个类型的枚举:
var values = (SomeType[])Enum.GetValues(typeof(SomeType));
This works perfectly if i hard-code the enum type. 如果我硬编码枚举类型,这非常有效。 But I need to be able to set the type in run time.
但我需要能够在运行时设置类型。 i tried the following but this doesn't work:
我尝试了以下但这不起作用:
var values = (typeof(T)[])Enum.GetValues(typeof(T));
typeof(T)
will generally return you a Type
object, so compiler thinks you want to apply indexing to that object. typeof(T)
通常会返回一个Type
对象,因此编译器认为您要对该对象应用索引。
Try using: 尝试使用:
Enum.GetValues(typeof(T)).Cast<T>()
You can use the Cast<T>()
method for result custing and the typeof(T).IsEnum
method for type checking ( T
must be an enumerated type). 您可以使用
Cast<T>()
方法进行结果保留,使用typeof(T).IsEnum
方法进行类型检查( T
必须是枚举类型)。
The target method: 目标方法:
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>();
}
Usage example: 用法示例:
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
}
Your T
is already of type Type
. 你的
T
已经是Type
。 There is no need to use another typeof
. 有没有必要使用其他
typeof
。 A simple cast to a T[]
should suffice: 对
T[]
简单转换就足够了:
T[] values = (T[]) Enum.GetValues(typeof(T));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.