Um Enum por definição, só armazena valores interiros. Com o Framework 3.5 temos um novo recurso chamado Extension Methods. Com esse recurso, é possível fazermos uma personalização que nos permitirá o armazenamento de valores String no Enum.
Primeiro passo é a criação de um Atributo que irá armazenar os valores da string:
public static string GetStringValue(this Enum value)
{
// Retorna o Tipo
Type type = value.GetType();
// Retorna informações do Campo deste Tipo
FieldInfo fieldInfo = type.GetField(value.ToString());
// Retorna os Atributos
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Retorna o primeiro se for encontrado
return attribs.Length > 0 ? attribs[0].StringValue : null;
}
Depois, criar a classe Extension e o Extesion Method:
public static class MyExtension
{
public static string GetStringValue(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;
}
}
Com isso, basta criar o Enum colocando os devidos atributos para armazenar as strings
public enum Test : int
{
[StringValue("FOO_VALOR1")]
Foo = 1,
[StringValue("SOME_VALOR2")]
Something = 2
}
Agora, basta Utilizar:
Test t = Test.Foo; Console.WriteLine(t.GetStringValue());
É um recurso interessante para casos pontuais onde precisar armazenar strings para posterior utilização.
Até a próxima
Saudações,
ResponderExcluirO meu comentário não terá a ver com este post especifico, mas com outra matéria do c#.Se for possivel gostaria que me explica-se a função do dataset e a sua importância quando se trabalha com base de dados.
O meu obrigado.