Can you simplify this code but without changing ENUM?
Here is to verify if exist
- private bool EnumHasValue(Type pTipoDoEnum, string valorDoEnum)
- {
- foreach (var val in Enum.GetValues(pTipoDoEnum))
- {
- var member = pTipoDoEnum.GetMember(val.ToString()).FirstOrDefault();
- var attribute = member.GetCustomAttributes(false).OfType<XmlEnumAttribute>().FirstOrDefault();
- if (valorDoEnum == attribute.Name)
- {
- return true;
- }
- }
- return false;
- }
Now, find string and return value:
- private object EnumFromString(Type pTipoDoEnum, string valorDoEnum)
- { foreach (var val in Enum.GetValues(pTipoDoEnum))
- {
- var member = pTipoDoEnum.GetMember(val.ToString()).FirstOrDefault();
- var attribute = member.GetCustomAttributes(false).OfType<XmlEnumAttribute>().FirstOrDefault();
- if (valorDoEnum == attribute.Name)
- {
- return val;
- }
- }
- throw new Exception("Não existe o valor " + Text + " para o tipo " + pTipoDoEnum.ToString() + ". Utilize o método EnumHasValue antes da conversão.");
- }
this is the call:
- string text = "02";
- Velocidade velocidade = new Velocidade();
- if (EnumHasValue(typeof(Velocidade),text)) velocidade = (Velocidade)EnumFromString(typeof(Velocidade), text);
-
- textBox1.Text = "O resultado é: \"" + velocidade.ToString() + "\"";