简体   繁体   English

如果只在运行时知道枚举类型,如何枚举枚举?

[英]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>()

public static IEnumerable<T> GetValues<T>()
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

See fiddle 小提琴

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.

相关问题 将字符串转换为枚举,但枚举类型仅在运行时已知 - Convert string to enum, but when enum type is only known at runtime 将整数转换为仅在运行时已知的盒装枚举类型 - Converting an integer to a boxed enum type only known at runtime 如何将ProjectTo从基类型转换为仅在运行时已知的类型? - How to ProjectTo from a base type to a type only known at runtime? 当只在运行时知道Type时,如何使用表达式树来调用泛型方法? - How can I use an expression tree to call a generic method when the Type is only known at runtime? 如何在运行时知道类型时将对象强制转换为类型? - How to cast to an object to a type when type is known during runtime? 如果直到运行时才知道类型,如何创建Expression.Lambda? - How to create a Expression.Lambda when a type is not known until runtime? 在运行时知道类型时,如何将db中的值映射到我的对象? - How to map values in the db, to my objects when the type is known at runtime? 将FormCollection转换为仅在运行时已知的类型的对象 - Convert FormCollection to object of type known only at runtime 动态对象强制转换为仅在运行时已知的类型 - Dynamic object cast to type known at runtime only 动态调度按类型仅在运行时已知 - Dynamic dispatch by Type only known at runtime
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM