迭代枚举?

我正在尝试迭代枚举,并使用其每个值作为参数调用方法。 必须有一个比我现在更好的方法来做到这一点:

foreach (string gameObjectType in Enum.GetNames(typeof(GameObjectType))) { GameObjectType kind = (GameObjectType) Enum.Parse(typeof (GameObjectType), gameObjectType); IDictionary gameObjectData = PersistentUtils.LoadGameObject(kind, persistentState); } //... public static IDictionary LoadGameObject(GameObjectType gameObjectType, IPersistentState persistentState) { /* ... */ } 

将枚举名称作为字符串,然后将它们解析回枚举,感觉很可怕。

好吧,你可以使用Enum.GetValues

 foreach (GameObjectType type in Enum.GetValues(typeof(GameObjectType)) { ... } 

虽然它不是强类型的 – 而且IIRC它很慢。 另一种方法是使用我的UnconstrainedMelody项目 :

 // Note that type will be inferred as GameObjectType :) foreach (var type in Enums.GetValues()) { ... } 

如果你在enums上做了很多工作,那么UnconstrainedMelody就不错了,但对于单次使用来说可能有点过分了…

为了防止其他人疯狂到想要在C ++ / CLI中执行此操作,这里有一个工作的端口:

 using namespace System; enum class GameObjectType { num1 = 1, num2 = 2, }; Array^ objectTypes = Enum::GetValues(GameObjectType::typeid); for each( GameObjectType^ objectType in objectTypes) { // Do something }