12

構成に次の構造が必要です。

<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に関する情報をいくつか見つけましたが、それは私が探しているものではありません。

4

2 に答える 2

8

これはうまくいきました-
コード:

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セクションの名前を変更したいだけなら、これは魅力のように機能します。

于 2011-09-20T05:02:30.907 に答える
2

から派生するクラスを作成する必要がありますConfigurationSection

ここで完全な例を参照してください:方法:ConfigurationSectionを使用してカスタム構成セクションを作成する

于 2011-09-19T12:55:22.813 に答える