迭代枚举?
我正在尝试迭代枚举,并使用其每个值作为参数调用方法。 必须有一个比我现在更好的方法来做到这一点:
foreach (string gameObjectType in Enum.GetNames(typeof(GameObjectType))) { GameObjectType kind = (GameObjectType) Enum.Parse(typeof (GameObjectType), gameObjectType); IDictionary gameObjectData = PersistentUtils.LoadGameObject(kind, persistentState); } //... public static IDictionary LoadGameObject(GameObjectType gameObjectType, IPersistentState persistentState) { /* ... */ }
将枚举名称作为字符串,然后将它们解析回枚举,感觉很可怕。
好吧,你可以使用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()) { ... }
如果你在enums上做了很多工作,那么UnconstrainedMelody就不错了,但对于单次使用来说可能有点过分了…
为了防止其他人疯狂到想要在C ++ / CLI中执行此操作,这里有一个工作的端口:
上述就是C#学习教程:迭代枚举?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
using namespace System; enum class GameObjectType { num1 = 1, num2 = 2, }; Array^ objectTypes = Enum::GetValues(GameObjectType::typeid); for each( GameObjectType^ objectType in objectTypes) { // Do something }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/962064.html