在 C# 2.0 中生成随机枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/319814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate random enum in C# 2.0
提问by user10178
Could someone please point me toward a cleaner method to generate a random enum member. This works but seems ugly.
有人可以请我指出一种更清洁的方法来生成随机枚举成员。这有效,但看起来很丑。
Thanks!
谢谢!
public T RandomEnum<T>()
{
string[] items = Enum.GetNames(typeof( T ));
Random r = new Random();
string e = items[r.Next(0, items.Length - 1)];
return (T)Enum.Parse(typeof (T), e, true);
}
采纳答案by Mark Cidade
public T RandomEnum<T>()
{
T[] values = (T[]) Enum.GetValues(typeof(T));
return values[new Random().Next(0,values.Length)];
}
Thanks to @[Marc Gravell] for ponting out that the max in Random.Next(min,max) is exclusive.
感谢@[Marc Gravell] 指出 Random.Next(min,max) 中的最大值是独占的。
回答by Marc Gravell
Marxidad's answer is good (note you only need Next(0,values.Length)
, since the upper bound is exclusive) - but watch out for timing. If you do this in a tight loop, you will get lots of repeats. To make it more random, consider keeping the Random object in a field - i.e.
马克思的回答很好(请注意,您只需要Next(0,values.Length)
,因为上限是排他性的)-但要注意时间。如果你在一个紧密的循环中这样做,你会得到很多重复。为了使它更随机,请考虑将 Random 对象保留在一个字段中 - 即
private Random rand = new Random();
public T RandomEnum<T>()
{
T[] values = (T[]) Enum.GetValues(typeof(T));
return values[rand.Next(0,values.Length)];
}
If it is a static field, you will need to synchronize access.
如果是静态字段,则需要同步访问。
回答by BCS
I'm not sure about c# but other languages allow gaps in enum values. To account for that:
我不确定 c#,但其他语言允许枚举值存在差距。考虑到这一点:
enum A {b=0,c=2,d=3,e=42};
switch(rand.Next(0,4))
{
case 0: return A.b;
case 1: return A.c;
case 2: return A.d;
case 3: return A.e;
}
The major down side is keeping it up to date!
主要的缺点是保持最新!
Not near as neat but more correct in that corner case.
在那个角落情况下,没有那么整洁,但更正确。
As pointed out, the examples from above index into an array of valid values and this get it right. OTOH some languages (coughD cough) don't provide that array so the above is useful enough that I'll leave it anyway.
正如所指出的,上面的例子索引到一个有效值的数组中,这是正确的。OTOH 某些语言(咳D咳)不提供该数组,因此上述内容足够有用,无论如何我都会保留它。
回答by pixie
Silverlight does not have GetValues(), but you can use reflection to get a random enum instead.
Silverlight 没有 GetValues(),但您可以使用反射来获取随机枚举。
private Random rnd = new Random();
public T RndEnum<T>()
{
FieldInfo[] fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
int index = rnd.Next(fields.Length);
return (T) Enum.Parse(typeof(T), fields[index].Name, false);
}
回答by Alex
Enum.Parse(typeof(SomeEnum), mRandom.Next(min, max).ToString()).ToString()