我试图遍历一个枚举,并使用其每个值作为参数调用一个方法。必须有比现在更好的方法:

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) { /* ... */ }

将枚举名称获取为字符串,然后将其解析回枚举,感觉很丑。

最佳答案

好吧,您可以使用 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>())
{
    ...
}

如果您要使用枚举执行大量工作,那么UnconstrainedMelody很好,但是对于单次使用来说可能会过大...

07-28 09:55