Languages
[Edit]
PT

C#/.NET - Obter elemento aleatório de enum

6 points
Created by:
Alyona
1170

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:

  1. obter objeto do tipo enum ;
  2. obter matriz de valores disponíveis;
  3. 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

Referências:

  1. Enum.GetValues() Method - Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join