How do I select a random value from an enumeration?

前端 未结 9 823
眼角桃花
眼角桃花 2020-12-04 07:54

Given an arbitrary enumeration in C#, how do I select a random value?

(I did not find this very basic question on SO. I\'ll post my answer in a minute as reference f

9条回答
  •  隐瞒了意图╮
    2020-12-04 08:22

    Personally, I'm a fan of extension methods, so I would use something like this (while not really an extension, it looks similar):

    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() {
            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();
                Console.WriteLine(option);
            }
        }
    
    }
    

提交回复
热议问题