迭代枚举?

发布于 2024-08-28 13:40:09 字数 557 浏览 5 评论 0原文

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遗失的美好 2024-09-04 13:40:11

那么,您可以使用 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<GameObjectType>())
{
    ...
}

如果您要做的是使用枚举进行了大量工作,但对于单次使用来说可能有点过分了......

Well, you can use Enum.GetValues:

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

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 is nice if you're doing a lot of work with enums, but it might be overkill for a single usage...

微暖i 2024-09-04 13:40:11

以防万一其他人疯狂到想要这样做想要在 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
}

Just in case anyone else is crazy enough to want to do wants to do this in C++/CLI, here's a port which works:

using namespace System;

enum class GameObjectType
{
    num1 = 1,
    num2 = 2,
};

Array^ objectTypes = Enum::GetValues(GameObjectType::typeid);
for each( GameObjectType^ objectType in objectTypes)
{
    // Do something
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文