.net - 如何创建一个行为类似于 AppSettings 部分的自定义部分?

标签 .net namevaluecollection

我想在我的配置中有以下结构:

<MySection>  
  <add key="1" value="one" />  
  <add key="2" value="two" />
  <add key="3" value="three" />
</MySection>

我有一个限制,MySection 不能使用 AppSettingsSection,因为它必须从不同的父自定义部分继承。我需要将此部分解析为 NameValueCollection 以便当我调用以下内容时:
ConfigurationManager.GetConfig("MySection")

它应该返回一个 NameValueCollection。怎么做呢?我在 NameValueConfigurationCollection 上找到了一些信息,但这不是我要找的。

最佳答案

这有效-
代码:

class Program
{
    static void Main(string[] args)
    {
        NameValueCollection nvc = ConfigurationManager.GetSection("MyAppSettings") as NameValueCollection;
        for(int i=0; i<nvc.Count; i++)
        {
            Console.WriteLine(nvc.AllKeys[i] + " " + nvc[i]);
        } 
        Console.ReadLine();
    }
}

class ParentSection : ConfigurationSection
{ 
    //This may have some custom implementation
}

class MyAppSettingsSection : ParentSection
{
    public static MyAppSettingsSection GetConfig()
    {
        return (MyAppSettingsSection)ConfigurationManager.GetSection("MyAppSettings");
    }


    [ConfigurationProperty("", IsDefaultCollection = true)]
    public NameValueConfigurationCollection Settings
    {
        get
        {
            return (NameValueConfigurationCollection)base[""];
        }
    }
}

配置:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!-- <section name="MyAppSettings" type="CustomAppSettings.MyAppSettingsSection, CustomAppSettings"/> -->
    <section name="MyAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

  </configSections>

  <MyAppSettings>
    <add key="1" value="one"/>
    <add key="2" value="two"/>
    <add key="3" value="three"/>
    <add key="4" value="four"/>
  </MyAppSettings>
</configuration>

我主要担心的是我的部分需要从自定义部分继承,并且我想在调用 ConfigurationManager.GetSection("MyAppSettings") 时返回 NameValueCollection。
我将 type 属性更改为 AppSettingsSection,即使它在图片中无处可见并且可以正常工作。现在我需要弄清楚它是如何工作的,但现在好消息是我有一个工作样本:)

更新 :不幸的是,这不是实现预期目标的预期方式,因为现在自定义部分根本没有出现,所以不幸的是,这不是最好的方法。

当然,如果您只是想重命名您的 appsettings 部分,这将非常有用。

关于.net - 如何创建一个行为类似于 AppSettings 部分的自定义部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7471234/

相关文章:

c# - 如何使用带有 List<MyStructure> 的 LINQ 投影来获取 NameValueCollection?

java - 将 URI 字符串解析为名称-值集合

c# - 如何设置NameValueCollection的长度

java - 将 URI 字符串解析为名称-值集合

c# - 区分卸载/安装和升级应用程序

c# - 从服务器而不是本地驱动器路径在 MVC ASP.NET 中加载 XML 文件

c# - 如何跳出 IF 语句

.net - static char * 与 C++ VS2005 中的#define

c# - 在线程中发出和处理异步 Web 服务请求

c# - 如何将NameValueCollection转换为XML?