How do I select a random value from an enumeration?

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

提交回复
热议问题