Enum.Parse未能投串Enum、Parse

2023-09-04 02:42:18 作者:结局却一个人

我想加载一些的AppSettings到一个对象。这些设置是这样的:

I'm trying to load some AppSettings into an object. The settings look like this:

<?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 再presents则允许设置多个枚举值。我想通过以下code加载这些到我的对象:

The Logging_levels represents several enum values that are allowed by the settings. I'm trying to load these into my object by using the following code:

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

不过,这是行不通的,我只得到LogLevel.Info回来,Loglevel.Error的不是值| LogLevel.Warning | LogLevel.Info。枚举的定义如下:

But this is not working and I'm only getting LogLevel.Info returned, not the value of Loglevel.Error | LogLevel.Warning | LogLevel.Info. The enum is defined as followed:

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

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

Am I wrong by defining the values in hex? or did I miss something else?

推荐答案

枚举值会导致问题。

标记的值 枚举必须是两个大国,你不应该使用0任何值不是某种空/无/无指示灯等。

The values of a Flags enum must be powers of two, and you shouldn't use 0 for any value other than some kind of empty/none/nothing indicator.

这是否有什么区别?

[Flags]
public enum LogLevel
{
    None        =  0
    Error       =  1,
    Warning     =  2,
    Info        =  4,
    Debug       =  8,
    Performance = 16
}
 
精彩推荐
图片推荐