【问题标题】:Get enum values from web.config at run time在运行时从 web.config 获取枚举值
【发布时间】:2011-11-16 08:23:31
【问题描述】:

我有一个枚举,我想在运行时从 web.config 获取。 我开始阅读有关构建提供程序的信息,但这似乎适用于类。 谁能给我举个例子,或者至少给我指出正确的方向。

现在我在 web.config 中有一个逗号分隔的值列表,这不是类型安全的并且容易出错。

如果有其他方法可以获得这种类型的“动态枚举”,我愿意接受其他想法。

谢谢!

【问题讨论】:

标签: c# asp.net


【解决方案1】:

您可以使用ConfigurationManager 并将值转换为枚举:

<configuration> 
  <appSettings>
    <add key="YourEnum" value="BlueSky" />  
  </appSettings>
</configuration>
string configValue = ConfigurationManager.AppSettings["YourEnum"];
YourEnumType value = (YourEnumType)Enum.Parse(typeof(YourEnumType), configValue); 

【讨论】:

    【解决方案2】:

    如果我是你,我会设计自己的 Enum 类。这样您就可以将其序列化为 XML 或在运行时构建它。它还将确保您仍然具有类型安全性。

    通常,数据将存储在类中的字典类型或键/值对列表中。然后你可以在配置文件中存储一个值列表(看看如何读取列表数据)

    看看here 以获得一些想法。

    【讨论】:

      【解决方案3】:

      Microsoft.Extensions.Configuration 将反序列化存储在 JSON 字符串中的枚举,我找到了解决此问题的好方法。

      举个例子:

      public enum Format
      {
          UNKNOWN = 0,
          PNG,
          JPEG
      }
      
      public class ImageOptions
      {
          /* List of supported file types */
          public List<Format> SupportedFileTypes { get; set; }
      }
      
      /* Options config dict */
      public static Dictionary<string, string> DefaultImageServiceConfigDict = new Dictionary<string, string>
      {
          /* Image Options NOTE: Enums stored as strings!! */
          {"ImageServiceOptions:SupportedFileTypes:0", "png"},
          {"ImageServiceOptions:SupportedFileTypes:1", "jpeg"},
      };
      
      /* Read options */
      var builder = new ConfigurationBuilder();
      builder.AddInMemoryCollection(DefaultImageServiceConfigDict);
      configuration = builder.Build();
      
      /* Parses config, including enum deserialisation by name */
      imageConfig = config.GetSection(nameof(ImageOptions)).TryGet<ImageServiceOptions();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-07
        • 1970-01-01
        • 2012-05-05
        • 2012-12-28
        • 1970-01-01
        • 2010-11-01
        相关资源
        最近更新 更多