我正在尝试迭代枚举,并使用其每个值作为参数调用方法.必须有一个比我现在更好的方法来做到这一点:
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) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
将枚举名称作为字符串,然后将它们解析回枚举,感觉很可怕.
Jon*_*eet 34
好吧,你可以使用Enum.GetValues:
foreach (GameObjectType type in Enum.GetValues(typeof(GameObjectType))
{
...
}
Run Code Online (Sandbox Code Playgroud)
虽然它不是强类型的 - 而且IIRC它很慢.另一种方法是使用我的UnconstrainedMelody项目:
// Note that type will be inferred as GameObjectType :)
foreach (var type in Enums.GetValues<GameObjectType>())
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果你在enums上做了大量的工作,那么UnconstrainedMelody就不错了,但是对于单次使用来说可能有点过头了......