Last active
May 3, 2020 00:19
-
-
Save ThiagoBarradas/03b832a47d6f40f213db7201db494b3f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sem flags e com uso sequencial dos números | |
// Podendo ter até 4.294.967.296 valores diferentes | |
public enum Cor | |
{ | |
Vermelho = 1, | |
Verde = 2, | |
Azul = 3, | |
Amarelo = 4, | |
Branco = 5 | |
} | |
// Veja como usar primeiro e por ultimo estará a implementação | |
Flags<Cor> minhascores = new Flags<Cor> | |
{ | |
Cor.Vermelho, Cor.Verde, Cor.Azul | |
}; | |
// para adicionar sem duplicações | |
minhascores.AddOrReplace(Cor.Amarelo); | |
minhascores.AddOrReplace(Cor.Branco); | |
// para remover | |
minhascores.Remove(Cor.Vermelho); | |
// para validar se faz uma cor parte da coleção | |
if (minhascores.Contains(Cor.Azul)) | |
{ | |
// faz algo | |
} | |
// para verificando o "None" que para esse caso não precisa existir no enumerador | |
if (!minhascores.Any()) | |
{ | |
// entra aqui se estiver vazio | |
} | |
// Usando o ToString() ou fazendo atribuição implicita obtemos o mesmo formato que as Flags | |
var minhasCoresToString = minhascores.ToString(); | |
string minhasCoresString = minhascores; // implicito | |
Console.WriteLine(minhasCoresToString); // Verde, Azul, Amarelo, Branco | |
Console.WriteLine(minhasCoresString); // Verde, Azul, Amarelo, Branco | |
// Criar uma nova coleção a partir de uma string explicitamente | |
Flags<Cor> novasCores1 = (Flags<Cor>)"Verde, Azul, Amarelo, Branco"; | |
Flags<Cor> novasCores2 = "Verde, Azul, Amarelo, Branco"; | |
// Implementação | |
public class Flags<TEnum> : List<TEnum> where TEnum : struct | |
{ | |
public Flags() | |
{ | |
if (!typeof(TEnum).IsEnum) | |
{ | |
throw new ArgumentException("T must be an enumerated type"); | |
} | |
} | |
public Flags(string flagsString) : this() | |
{ | |
if (!string.IsNullOrWhiteSpace(flagsString)) | |
{ | |
var flags = flagsString.Split(","); | |
foreach (var flag in flags) | |
{ | |
var flagEnum = Enum.Parse<TEnum>(flag); | |
this.AddOrReplace(flagEnum); | |
} | |
} | |
} | |
public void AddOrReplace(TEnum item) | |
{ | |
if (this.Contains(item)) | |
{ | |
return; | |
} | |
this.Add(item); | |
} | |
public override string ToString() | |
{ | |
return string.Join(", ", this.AsEnumerable()); | |
} | |
public static implicit operator string(Flags<TEnum> flags) => flags.ToString(); | |
public static implicit operator Flags<TEnum>(string flagsString) => new Flags<TEnum>(flagsString); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment