Can you simplify this code but without changing ENUM?
- /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute()] public enum Velocidade { /// [System.Xml.Serialization.XmlEnumAttribute("01")] Baixa, /// [System.Xml.Serialization.XmlEnumAttribute("02")] Normal, /// [System.Xml.Serialization.XmlEnumAttribute("03")] Rapida, }
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
().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
().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);
- // O resultado é: "Normal"
- textBox1.Text = "O resultado é: \"" + velocidade.ToString() + "\"";
Sundaram SubramanianPosted Oct 5, 2017, 1:48 PM