【问题标题】:How do I add two sections of custom settings to app.config and read them into a class in asp.net?如何将自定义设置的两个部分添加到 app.config 并将它们读入 asp.net 中的类?
【发布时间】:2013-03-04 04:26:03
【问题描述】:

我需要在 app.config 中存储 2 个设置部分,并且根据初始化类时传递的值,我将加载其中一个设置部分。

这是我理想中需要达到的目标:

Public Class SiteSettings

    Sub New(ByVal Id As Integer)
            If Id = 1 Then
                'Load in group1 settings.
                'Ideally the settings will be available as properties
            Else
                'Load in group2 settings
            End If
    End Sub
    ...
End Class

代码

Dim objSettings = New SiteSettings(Id)

'just to demo what I'm trying to achieve
response.Write(objSettings.setting1)

App.config

<siteSettings>
    <section name="group1">
        <setting1 value="abc" />
    </section>
    <section name="group2">
        <setting1 value="xyz" />
    </section>
</siteSettings>

【问题讨论】:

    标签: asp.net vb.net app-config custom-sections


    【解决方案1】:

    这可能超出了 app.config 文件的支持范围。但是,您当然可以在应用程序目录中包含您自己的 xml 文件,并使用 XPath 对其进行解析,以按照您的描述加载您的设置。

    【讨论】:

      【解决方案2】:

      在您自己的设置中阅读应该不难。有很多代码用于阅读自定义配置设置 - 只需查看此页面上“相关”下的链接即可。如果您的设置对象是可序列化的,您可以使用自定义设置支持从 app.config 检索实例。

      如果您想实例化一个对象并将所有设置读取逻辑封装在构造函数中,您可能必须为您的实际自定义配置设置编写一个包装器,如下所示:

      public interface ISettings
      {
           int Setting1 { get; set; }
      }
      
      [Serializable]
      public class ActualSettings : ISettings
      {
          public int Setting1 { get;set;}
      }
      
      public class SettingsAdapter : ISettings
      {
          private ISettings settings;
          public SettingsAdapter(int id)
          {
              if(id == 1)
                  settings = // code to retrieve instance #1 from app.config
              else
                  settings = // code to retrieve instance #2 from app.config
          }
      
          public int Setting1 { 
             get { return settings.Setting1; }
             set { settings.Setting1 = value; }
          }
      }
      

      【讨论】:

      • 哎呀,我是用 c# 做的。但你明白了。
      猜你喜欢
      • 2012-02-29
      • 2011-01-30
      • 2015-05-23
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 2015-08-11
      • 1970-01-01
      相关资源
      最近更新 更多