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:
Random random = new Random();
Type type = typeof(MyEnum);
Array values = type.GetEnumValues();
int index = random.Next(values.Length);
MyEnum value = (MyEnum)values.GetValue(index);
enum
aleatório com operador typeof
- exemplo
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:
using System;
namespace Test
{
public enum CustomColor
{
Green,
Blue,
Red,
Yellow
}
class Program
{
public static void Main(string[] args)
{
Random random = new Random();
Type type = typeof(CustomColor);
Array values = type.GetEnumValues();
//Array values = Enum.GetValues(type);
for(int i = 0; i < 10; ++i)
{
int index = random.Next(values.Length);
CustomColor value = (CustomColor)values.GetValue(index);
Console.WriteLine(value);
}
}
}
}
Resultado:
Green
Green
Yellow
Yellow
Red
Blue
Green
Yellow
Blue
Green