public static Random RNG = new Random();
public static T RandomEnum<T>()
{
Type type = typeof(T);
Array values = Enum.GetValues(type);
lock(RNG)
{
object value= values.GetValue(RNG.Next(values.Length));
return (T)Convert.ChangeType(value, type);
}
}
public enum Options {
Zero,
One,
Two,
Three,
Four,
Five
}
public static class RandomEnum {
private static Random _Random = new Random(Environment.TickCount);
public static T Of<T>() {
if (!typeof(T).IsEnum)
throw new InvalidOperationException("Must use Enum type");
Array enumValues = Enum.GetValues(typeof(T));
return (T)enumValues.GetValue(_Random.Next(enumValues.Length));
}
}
[TestClass]
public class RandomTests {
[TestMethod]
public void TestMethod1() {
Options option;
for (int i = 0; i < 10; ++i) {
option = RandomEnum.Of<Options>();
Console.WriteLine(option);
}
}
}
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());
}
}
}
public static class RandomExtensions
{
public static T NextEnum<T>(this Random random)
{
var values = Enum.GetValues(typeof(T));
return (T)values.GetValue(random.Next(values.Length));
}
}
用法示例:
var random = new Random();
var myEnumRandom = random.NextEnum<MyEnum>();
using System;
enum Test {
Value1,
Value2,
Value3
}
class Program {
public static void Main (string[] args) {
var max = Enum.GetValues(typeof(Test)).Length;
var value = (Test)new Random().Next(0, max - 1);
Console.WriteLine(value);
}
}
static Random random = new Random();
// Somewhat unintuitively, we need to constrain the type parameter to
// both struct *and* Enum - struct is required b/c the type can't be
// nullable, and Enum is required b/c GetValues expects an Enum type.
// You'd think that Enum itself would satisfy the non-nullable
// constraint, but alas, me compiler tells me otherwise - perhaps
// someone more knowledgeable can explain why this is in a comment?
static TEnum RandomEnumValue<TEnum>() where TEnum : struct, Enum
{
TEnum[] vals = Enum.GetValues<TEnum>();
return vals[random.Next(vals.Length)];
}
public static class RandomExtensions
{
public static TEnum NextEnumValue<TEnum>(this Random random)
where TEnum : struct, Enum
{
TEnum[] vals = Enum.GetValues<TEnum>();
return vals[random.Next(vals.Length)];
}
}
public static class RandomExtensions
{
private static Random Random = new Random();
public static T GetRandom<T>() where T : struct, Enum
{
T[]? v = Enum.GetValues<T>();
return (T)v.GetValue(Random.Next(v.Length));
}
}