C# 自定义app.config节,其中包含一个简单的;加上「;元素

C# 自定义app.config节,其中包含一个简单的;加上「;元素,c#,app-config,C#,App Config,如何创建一个自定义app.config节,它只是一个简单的add元素列表 我发现一些定制部分的示例(例如)如下所示: 但是如何避免额外的集合元素(“companys”),使其看起来与appSettings和connectionStrings部分相同?换句话说,我想: 基于OP配置文件的代码完整示例: <configuration> <configSections> <section name="registerCompanies"

如何创建一个自定义app.config节,它只是一个简单的
add
元素列表

我发现一些定制部分的示例(例如)如下所示:


但是如何避免额外的集合元素(“companys”),使其看起来与
appSettings
connectionStrings
部分相同?换句话说,我想:


基于OP配置文件的代码完整示例:

<configuration>
    <configSections>
        <section name="registerCompanies" 
                 type="My.MyConfigSection, My.Assembly" />
    </configSections>
    <registerCompanies>
        <add name="Tata Motors" code="Tata"/>
        <add name="Honda Motors" code="Honda"/>
    </registerCompanies>
</configuration>
<configuration>
    <configSections>
        <section name="registerCompanies" 
                 type="My.MyConfigSection, My.Assembly" />
    </configSections>
    <registerCompanies>
        <add name="Tata Motors" code="Tata"/>
        <add name="Honda Motors" code="Honda"/>
    </registerCompanies>
</configuration>
下面是一个如何从代码访问配置信息的示例

var config = ConfigurationManager.GetSection("registerCompanies") 
                 as MyConfigSection;

Console.WriteLine(config["Tata Motors"].Code);
foreach (var e in config.Instances) { 
   Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code); 
}
MyConfigSection config = 
   ConfigurationManager.GetSection("registerCompanies") as MyConfigSection;

Console.WriteLine(config.Instances["Honda Motors"].Code);
foreach (MyConfigInstanceElement e in config.Instances)
{
   Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code);
}

根据Jay Walker的回答,需要通过迭代“实例”集合来访问元素。即

var config = ConfigurationManager.GetSection("registerCompanies") 
                 as MyConfigSection;

foreach (MyConfigInstanceElement e in config.Instances) { 
   Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code); 
}
根据以上答案,这是一个完整的工作示例,它增加了编制索引的功能:


不需要自定义配置部分

app.config


检索值

//AppSettingsSection可以强制转换为NameValueCollection
NameValueCollection设置集合=
(NameValueCollection)ConfigurationManager.GetSection(“YourAppSettings”);
//一组钥匙。无多重记录
//{“一”、“二”、“三”、“重复”}
string[]allKeys=settingCollection.allKeys;
//键/值对
//1:1
//2:2
//3:3
//副本:bb
foreach(所有键中的字符串键)
{
Console.WriteLine(键+”:“+设置集合[key]);
}
//复制行为
var items=settingCollection.Count;
Assert(items==4);//没有重复的。最后一个元素获胜。
Assert(settingCollection[“duplicate”]=“bb”);

另请参见@Jay Walker如何访问您需要的项目,即:-config.Instances[“Tata Motors”]是否可以执行此操作?应指出
应位于
标签之后,以使其正常工作!还应指出,AFAIK-此代码“config[“Tata Motors”]”不会编译b/c。config的索引器受内部保护。您必须自己找到一种方法来枚举集合中的项目。@JayWalker很好。您的示例中针对节类型的“My.MyConfiguration,My.Assembly”抛出了我。我只是想用“MyAssembly.MyConfiguration,MyAssembly”来解释我的尝试。我想这并不能严格回答OP的问题,但我认为这是一个有效的解决方案,而且更简单。至少它帮助了我@斯泰尔:你说得对。它并没有严格地回答这个问题。如果必须使用属性名称/代码而不是我的解决方案键/值,则必须使用真正自定义的部分。但是,我假设您控制了配置文件,并且有比创建自定义类更好的事情要做。非常简单和干净!不需要任何额外的自定义节/元素bloatware。如果愿意,只需更改版本号,也可以更新到版本=4.0.0.0。如果你只需要额外的简单列表,这是最好的答案。“System.Configuration.ConnectionStringsSection”也可以这样做,尽管重复项的处理方式与应用程序设置略有不同。@Sharpiro程序集版本有问题吗?我原以为程序集绑定会很快,即使对于框架的更新版本也是如此。这太棒了。现在我们只需要更新、添加和删除实例的示例代码。感谢您的解决方案!不管是谁在MS做的这真的是不必要的复杂。
using System.Configuration;
using System.Linq;
namespace My
{
   public class MyConfigSection : ConfigurationSection
   {
      [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
      public MyConfigInstanceCollection Instances
      {
         get { return (MyConfigInstanceCollection)this[""]; }
         set { this[""] = value; }
      }
   }
   public class MyConfigInstanceCollection : ConfigurationElementCollection
   {
      protected override ConfigurationElement CreateNewElement()
      {
         return new MyConfigInstanceElement();
      }

      protected override object GetElementKey(ConfigurationElement element)
      {
         //set to whatever Element Property you want to use for a key
         return ((MyConfigInstanceElement)element).Name;
      }

      public new MyConfigInstanceElement this[string elementName]
      {
         get
         {
            return this.OfType<MyConfigInstanceElement>().FirstOrDefault(item => item.Name == elementName);
         }
      }
   }

   public class MyConfigInstanceElement : ConfigurationElement
   {
      //Make sure to set IsKey=true for property exposed as the GetElementKey above
      [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
      public string Name
      {
         get { return (string)base["name"]; }
         set { base["name"] = value; }
      }

      [ConfigurationProperty("code", IsRequired = true)]
      public string Code
      {
         get { return (string)base["code"]; }
         set { base["code"] = value; }
      }
   }
}
MyConfigSection config = 
   ConfigurationManager.GetSection("registerCompanies") as MyConfigSection;

Console.WriteLine(config.Instances["Honda Motors"].Code);
foreach (MyConfigInstanceElement e in config.Instances)
{
   Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code);
}