Dar*_*rov 267
Array values = Enum.GetValues(typeof(Bar));
Random random = new Random();
Bar randomBar = (Bar)values.GetValue(random.Next(values.Length));
Run Code Online (Sandbox Code Playgroud)
maf*_*afu 56
使用Enum.GetValues检索所有值的数组.然后选择一个随机数组项.
static T RandomEnumValue<T> ()
{
var v = Enum.GetValues (typeof (T));
return (T) v.GetValue (new Random ().Next(v.Length));
}
Run Code Online (Sandbox Code Playgroud)
测试:
for (int i = 0; i < 10; i++) {
var value = RandomEnumValue<System.DayOfWeek> ();
Console.WriteLine (value.ToString ());
}
Run Code Online (Sandbox Code Playgroud)
- >
Tuesday
Saturday
Wednesday
Monday
Friday
Saturday
Saturday
Saturday
Friday
Wednesday
Run Code Online (Sandbox Code Playgroud)
更新:此答案最初用于OrderBy (x => _Random.Next()).FirstOrDefault ()
选择随机元素.只有在你被随意键改变而非理性地吸引时才使用它.在任何其他情况下,请使用Darin Dimitrov接受的答案,我将在稍后的答案中加入.
这是作为Extension Method
using的替代版本LINQ
。
using System;
using System.Linq;
public static class EnumExtensions
{
public static Enum GetRandomEnumValue(this Type t)
{
return Enum.GetValues(t) // get values from Type provided
.OfType<Enum>() // casts to Enum
.OrderBy(e => Guid.NewGuid()) // mess with order of results
.FirstOrDefault(); // take first item in result
}
}
public static class Program
{
public enum SomeEnum
{
One = 1,
Two = 2,
Three = 3,
Four = 4
}
public static void Main()
{
for(int i=0; i < 10; i++)
{
Console.WriteLine(typeof(SomeEnum).GetRandomEnumValue());
}
}
}
Run Code Online (Sandbox Code Playgroud)
二
一
四
四
四
三
二
四
一
三
小智 7
改编为 Random 类扩展:
public static class RandomExtensions
{
public static T NextEnum<T>(this Random random)
where T : struct, Enum
{
var values = Enum.GetValues<T>();
return values[random.Next(values.Length)];
}
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
var random = new Random();
var myEnumRandom = random.NextEnum<MyEnum>();
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
var rnd = new Random();
return (MyEnum) rnd.Next(Enum.GetNames(typeof(MyEnum)).Length);
Run Code Online (Sandbox Code Playgroud)
无需存储数组