gpt4 book ai didi

c# - Enum.Parse() 或 Switch

转载 作者:可可西里 更新时间:2023-11-01 08:34:19 24 4
gpt4 key购买 nike

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

  1. 这段代码:

    colorEnum color = (colorEnum)Enum.Parse(typeof(colorEnum), "Green");
  2. 或者这个:

    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,如果失败你可以正确处理错误。

示例:

     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);

关于c# - Enum.Parse() 或 Switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7497148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com