【问题标题】:Enum.Parse fails to cast stringEnum.Parse 无法转换字符串
【发布时间】:2011-11-23 13:20:46
【问题描述】:

我正在尝试将一些 AppSettings 加载到对象中。设置如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Logging_default_path" value="C:\Temp" />
    <add key="Logging_max_file_size" value="10485760" />
    <add key="Logging_levels" value="Error,Warning,Info"/>
    <add key="Logging_filename" value="RobinsonLog" />
  </appSettings>
</configuration>

Logging_levels 表示设置允许的几个枚举值。我正在尝试使用以下代码将这些加载到我的对象中:

Level = (LogLevel)Enum.Parse(typeof(LogLevel), settings["Logging_levels"]);

但这不起作用,我只返回 LogLevel.Info,而不是 Loglevel.Error 的值 |日志级别警告 |日志级别信息。枚举定义如下:

[Flags]
public enum LogLevel
{
    Error = 0x0,
    Warning = 0x1,
    Info = 0x2,
    Debug = 0x3,
    Performance = 0x4
}

我用十六进制定义值错了吗?还是我错过了什么?

【问题讨论】:

  • 您是否尝试过使用您的期望值创建一个枚举并将其转换为字符串?这应该显示正确的语法。
  • 您的标志值错误。 Warning | Info == Debug 和 Debug == Debug | Error 的写法。

标签: c# .net parsing enums


【解决方案1】:

您的enum 值会导致问题。

Flagsenum 的值必须是 2 的幂,并且除了某种空/无/无指示符之外,您不应将 0 用于任何值。

这有什么不同吗?

[Flags]
public enum LogLevel
{
    None        =  0
    Error       =  1,
    Warning     =  2,
    Info        =  4,
    Debug       =  8,
    Performance = 16
}

【讨论】:

  • 这成功了。似乎解析器确实不欣赏十六进制值。
  • 从技术上讲,它们不必必须是二的幂。例如,[Flags] enum FooBar { Foo = 5, Bar = 10 } 也可以正常工作。但这样做完全是不必要的复杂化。没有理由不使用二的幂。
  • @NekoNova,这与使用十六进制或十进制无关。这是关于指定正确的值。
  • @NekoNova:与值文字是否以十六进制编写无关。这些值必须是2 的幂。如果您将它们声明为 0x00、0x01、0x02、0x04、0x08 和 0x10,它的工作方式完全相同。
【解决方案2】:

适当的标志值可能会有所帮助(每个值应设置不同的位):

[Flags]
public enum LogLevel
{
    None = 0x0,
    Error = 0x1,
    Warning = 0x2,
    Info = 0x4,
    Debug = 0x8,
    Performance = 0x10
}

注意:您可以根据需要删除“无”。

【讨论】:

    【解决方案3】:

    http://msdn.microsoft.com/en-us/library/essfb559.aspx

    value 参数包含枚举成员的基础值或命名常量的字符串表示形式,或由逗号 (,) 分隔的命名常量列表。值中的每个值、名称或逗号之前或之后可以有一个或多个空格。如果 value 是一个列表,则返回值是指定名称与按位或运算组合的值。

    所以它应该可以工作,并且 ik 看起来确实如此:

    LogLevel level = (LogLevel)Enum.Parse(typeof(LogLevel), "Error,Warning");
    
    if ((level & LogLevel.Error) == LogLevel.Error)
    {
        Console.WriteLine("Error");
    }
    
    if ((level & LogLevel.Warning) == LogLevel.Warning)
    {
        Console.WriteLine("Warning");
    }
    
    if ((level & LogLevel.Info) == LogLevel.Info)
    {
        Console.WriteLine("Info");
    }
    

    给我“错误”和“警告”。但是,通过在 Visual Studio 中检查 level 变量,它只显示“警告”。也许这会让你失望。 ;-)


    编辑:@svick 和 @jv42 是对的,是你的标志值是错误的。

    【讨论】:

    • 调试报告正确的值。导致问题的标志值不正确
    【解决方案4】:

    问题不在于解析!问题是转换为文本,而不是。因为标志值不是不同的位掩码,所以没有 确定性 映射到字符串和返回。正如其他人所提到的,您应该选择如下值,例如:

    [Flags]
    public enum LogLevel
    {
        None = 0
        Error = 1 << 0,
        Warning = 1 << 1,
        Info = 1 << 2,
        // etc
    }
    

    见MSDN: Parsing Enumeration Values

    观看现场演示:https://ideone.com/8AkSQ

    using System;
    
    [Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
    
    public class Example
    {
       public static void Main()
       {
          string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
          foreach (string colorString in colorStrings)
          {
             try {
                Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);        
                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);
             }
             catch (ArgumentException) {
                Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
             }
          }
       }
    }
    

    输出:

    Converted '0' to None.
    Converted '2' to Green.
    8 is not an underlying value of the Colors enumeration.
    'blue' is not a member of the Colors enumeration.
    Converted 'Blue' to Blue.
    'Yellow' is not a member of the Colors enumeration.
    Converted 'Red, Green' to Red, Green.
    

    性能说明:

    如果性能很重要,请不要依赖 Enum.Parse :)

    见How should I convert a string to an enum in C#?

    【讨论】:

    • 根据the doc,至少从.Net 2.0开始就支持解析标志。
    • 阅读那篇文章,我有 flags 属性,但它没有解释如何将字符串解析为标志集合
    • 样本显示:Converted 'Red, Green' to Red, Green。您想从组合值中获取标志集合吗? zero 与解析有关
    • 您的代码没有按照我的意图执行。我可以毫无问题地解析单个值,它是导致问题的值的组合
    • @NekoNova:啊,标志值应该是不重叠的,以做你所期望的,正如其他人提到的,特别是 svick!
    猜你喜欢
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2018-02-19
    • 2012-01-07
    • 2018-06-15
    相关资源
    最近更新 更多