迭代枚举?

时间:2010-04-13 19:56:03

标签: c# syntax enums

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

foreach (string gameObjectType in Enum.GetNames(typeof(GameObjectType)))
{
     GameObjectType kind = (GameObjectType) Enum.Parse(typeof (GameObjectType), gameObjectType);
     IDictionary<string, string> gameObjectData = PersistentUtils.LoadGameObject(kind, persistentState);
}

//...

public static IDictionary<string, string> LoadGameObject(GameObjectType gameObjectType, IPersistentState persistentState) { /* ... */ }

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

2 个答案:

答案 0 :(得分:34)

好吧,你可以使用Enum.GetValues

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

虽然它没有强力打字 - 而且IIRC它很慢。另一种方法是使用我的UnconstrainedMelody project

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

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

答案 1 :(得分:2)

以防其他人疯狂到想要做希望在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
}
相关问题