How do I select a random value from an enumeration?

前端 未结 9 827
眼角桃花
眼角桃花 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

    Adapted as a Random class extension:

    public static class RandomExtensions
    {   
        public static T NextEnum(this Random random)
        {
            var values = Enum.GetValues(typeof(T));
            return (T)values.GetValue(random.Next(values.Length));
        }
    }
    

    Example of usage:

    var random = new Random();
    var myEnumRandom = random.NextEnum();
    

提交回复
热议问题