1
It is possible to produce simpler code for this function without changing the enum?
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
public enum Velocidade
{
    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("01")]
    Baixa,
    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("02")]
    Normal,
    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("03")]
    Rapida,
}
Below is a method to check if the value exists:
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;
}
In the method below the value corresponding to string is found
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.");
}
Here is how the method is called:
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() + "\"";
Would a simple and objective extension method no longer solve?
– novic
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.
– Maniero