迭代枚举? [英] Iterate over enum?

查看:130
本文介绍了迭代枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to iterate over an enum, and call a method using each of its values as a parameter. There has to be a better way to do it than what I have now:

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

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

Getting the enum names as strings, then parsing them back to enums, feels hideous.

推荐答案

嗯,你可以使用 Enum.GetValues

Well, you can use Enum.GetValues:

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

它不是强类型,而IIRC它相当慢,另一种方法是使用我的 UnconstrainedMelody项目

It's not strongly typed though - and IIRC it's pretty slow. An alternative is to use my UnconstrainedMelody project:

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

UnconstrainedMelody是如果您正在使用枚举进行大量工作,那么这很有用,但是对于单次使用来说,这可能是过度的...

UnconstrainedMelody is nice if you're doing a lot of work with enums, but it might be overkill for a single usage...

这篇关于迭代枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆