繁体   English   中英

Enum.Parse无法转换字符串

[英]Enum.Parse fails to cast string

我正在尝试将一些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 |的值 LogLevel.Warning | LogLevel.Info。 枚举定义如下:

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

通过以十六进制定义值,我错了吗? 还是我错过了别的什么?

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

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

注意:如果您愿意,可以删除“无”。

你的enum值会导致问题。

Flags enum的值必须是2的幂,并且除了某种空/无/无指示符之外的任何值都不应该使用0。

这有什么不同吗?

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

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

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

所以它应该工作,并且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是对的,这是你的标志值是错误的。

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

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

请参阅MSDN:解析枚举值

现场观看演示: 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 :)

请参阅如何将字符串转换为C#中的枚举?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM