How do I select a random value from an enumeration?

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

    You could just do this:

    var rnd = new Random();
    return (MyEnum) rnd.Next(Enum.GetNames(typeof(MyEnum)).Length);
    

    No need to store arrays

    0 讨论(0)
  • 2020-12-04 08:10

    Use Enum.GetValues to retrieve an array of all values. Then select a random array item.

    static Random _R = new Random ();
    static T RandomEnumValue<T> ()
    {
        var v = Enum.GetValues (typeof (T));
        return (T) v.GetValue (_R.Next(v.Length));
    }
    

    Test:

    for (int i = 0; i < 10; i++) {
        var value = RandomEnumValue<System.DayOfWeek> ();
        Console.WriteLine (value.ToString ());
    }
    

    ->

    Tuesday
    Saturday
    Wednesday
    Monday
    Friday
    Saturday
    Saturday
    Saturday
    Friday
    Wednesday
    
    0 讨论(0)
  • 2020-12-04 08:11

    Call Enum.GetValues; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.

    0 讨论(0)
  • 2020-12-04 08:15

    You can also cast a random value:

    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);
      }
    }
    

    But you should use a better randomizer like the one in this library of mine.

    0 讨论(0)
  • 2020-12-04 08:17
    Array values = Enum.GetValues(typeof(Bar));
    Random random = new Random();
    Bar randomBar = (Bar)values.GetValue(random.Next(values.Length));
    
    0 讨论(0)
  • 2020-12-04 08:18

    Here is a generic function for it. Keep the RNG creation outside the high frequency code.

    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);
        }
    }
    

    Usage example:

    System.Windows.Forms.Keys randomKey = RandomEnum<System.Windows.Forms.Keys>();
    
    0 讨论(0)
提交回复
热议问题