Enum.Parse()或Switch [英] Enum.Parse() or Switch

查看:163
本文介绍了Enum.Parse()或Switch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要将字符串转换为枚举,以下哪种方式更好?

For converting a string to an enum, which of the following ways is better?


  1. 此代码:

  1. This code:

colorEnum color = (colorEnum)Enum.Parse(typeof(colorEnum), "Green");


  • 或这个:

  • or this:

    string colorString = ...
    colorEnum color;        
    switch (colorString)
    {
        case "Green":
            color = colorEnum.Green;
            break;
        case "Red":
            color = colorEnum.Red;
            break;
        case "Orange":
            color = colorEnum.Orange;
            break;
        ....
    }
    



  • 推荐答案

    您应该使用Enum.TryParse,如果失败,您可以正确处理错误。

    You should use the Enum.TryParse, if it fails you can handle the error correctly.

    示例: / p>

    sample:

         ColorsEnum colorValue; 
         if (Enum.TryParse(colorString, out colorValue))        
            if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))  
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
            else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
         else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
    

    这篇关于Enum.Parse()或Switch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆