PT
C#/.NET - Obter elemento aleatório de enum
6 points
Neste artigo, veremos como obter o elemento aleatório de enum.
Solução rápida:
xxxxxxxxxx
1
Random random = new Random();
2
3
Type type = typeof(MyEnum);
4
Array values = type.GetEnumValues();
5
int index = random.Next(values.Length);
6
7
MyEnum value = (MyEnum)values.GetValue(index);
Nesta seção, obtemos um enum
aleatório com o operador typeof
.
Para obter valor, execute as seguintes etapas:
- obter objeto do tipo
enum
; - obter matriz de valores disponíveis;
- obter valor aleatório da matriz com o objeto aleatório.
Veja o exemplo prático abaixo:
xxxxxxxxxx
1
using System;
2
3
namespace Test
4
{
5
public enum CustomColor
6
{
7
Green,
8
Blue,
9
Red,
10
Yellow
11
}
12
13
class Program
14
{
15
public static void Main(string[] args)
16
{
17
Random random = new Random();
18
Type type = typeof(CustomColor);
19
20
Array values = type.GetEnumValues();
21
//Array values = Enum.GetValues(type);
22
23
for(int i = 0; i < 10; ++i)
24
{
25
int index = random.Next(values.Length);
26
CustomColor value = (CustomColor)values.GetValue(index);
27
28
Console.WriteLine(value);
29
}
30
}
31
}
32
}
Resultado:
xxxxxxxxxx
1
Green
2
Green
3
Yellow
4
Yellow
5
Red
6
Blue
7
Green
8
Yellow
9
Blue
10
Green