如何将自定义设置的两部分添加到app.config中,并将其读入asp.net中的类中?

如何将自定义设置的两部分添加到app.config中,并将其读入asp.net中的类中?,asp.net,vb.net,app-config,custom-sections,Asp.net,Vb.net,App Config,Custom Sections,我需要在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 availab

我需要在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>


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

在您自己的设置中读取它应该不难。有很多代码用于读取自定义配置设置-只需查看本页“相关”下的链接。如果设置对象可序列化,则可以使用自定义设置支持从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#做的。但你明白了。