来自 Flags 枚举的随机值
假设我有一个函数接受用 Flags 属性修饰的枚举。如果枚举的值是多个枚举元素的组合,我如何随机提取这些元素之一?我有以下内容,但似乎必须有更好的方法。
[Flags]
enum Colours
{
Blue = 1,
Red = 2,
Green = 4
}
public static void Main()
{
var options = Colours.Blue | Colours.Red | Colours.Green;
var opts = options.ToString().Split(',');
var rand = new Random();
var selected = opts[rand.Next(opts.Length)].Trim();
var myEnum = Enum.Parse(typeof(Colours), selected);
Console.WriteLine(myEnum);
Console.ReadLine();
}
Say I have a function that accepts an enum decorated with the Flags attribute. If the value of the enum is a combination of more than one of the enum elements how can I extract one of those elements at random? I have the following but it seems there must be a better way.
[Flags]
enum Colours
{
Blue = 1,
Red = 2,
Green = 4
}
public static void Main()
{
var options = Colours.Blue | Colours.Red | Colours.Green;
var opts = options.ToString().Split(',');
var rand = new Random();
var selected = opts[rand.Next(opts.Length)].Trim();
var myEnum = Enum.Parse(typeof(Colours), selected);
Console.WriteLine(myEnum);
Console.ReadLine();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以调用
Enum.GetValues
获取枚举定义值的数组,如下所示:You can call
Enum.GetValues
to get an array of the enum's defined values, like this:如果您不介意进行一点转换,并且您的枚举是基础 int 类型,则以下内容将起作用并且速度很快。
如果您只想设置一个标志,您可以执行以下操作:
If you don't mind a little casting, and your enum is of underlying int type, the following will work and is fast.
If you only want a single flag to be set, you could do the following:
如果我理解正确,问题是从标志枚举值返回随机枚举值,而不是从标志枚举返回随机成员。
编辑
显然,您应该检查枚举是否是有效值,例如:
编辑
简化
If I understand correctly, the question is about returning a random enum value from a flags enum value, not returning a random member from a flags enum.
Edit
And obviously you should check that the enum is a valid value, e.g.:
Edit
Simplified
就我而言 - 我有缺少成员的枚举,例如
0x01、0x02、0x08
,以及具有0x200000000
最大值的大型ulong
枚举。此代码适用于我的所有情况:
In my case - I have enums with missing members e.g
0x01, 0x02, 0x08
, and largeulong
enum with0x200000000
maximal value.This code works for all of my cases: