从选定组中获取随机枚举
给定一组大约 20 个我无法修改的枚举。
我正在寻找一个优雅的解决方案来从特定样本(即 2、7、18)生成随机枚举,
我可以将它们放入数组列表中,但我想我会问是否还有其他我可以尝试的东西。
Given a group of about 20 enums that I cannot modify.
Im looking for an elegant solution to generate a random enum from a specific sample (ie, 2, 7, 18)
I could put these into an arraylist, but thought I would ask if there is something else I could try.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
最简单的解决方案是将您想要选择的枚举放入某种数组或列表中,然后从中随机选择。
如果您只是从完整定义中随机选择,则必须检查答案并拒绝那些您不想要的答案。
The simplest solution is to put those enums you want to choose from into an array or list of some kind and randomly pick from that.
If you just randomly pick from the the full definition you'll have to check the answer and reject those you don't want.
如果您的值都是同一类型:
If your values are all of the same type:
您可以使用以下命令获取给定枚举类型的所有值:
You can get all the values for a given enum type with:
我开发了一个快速控制台应用程序,可以执行类似的操作,但无法证明它的性能如何:)
I knocked up a quick console app that does something like this, can't attest to how performant it is though :)
为什么搞得这么复杂...
用法:
Why do it so complicated...
Usage: