c# - 如何从 App.config 中读取这个自定义配置?

标签 c# .net custom-configuration

如何从 App.config 中读取这个自定义配置?

<root name="myRoot" type="rootType">
    <element name="myName" type="myType" />
    <element name="hisName" type="hisType" />
    <element name="yourName" type="yourType" />
  </root>

而不是这个:

<root name="myRoot" type="rootType">
  <elements>
    <element name="myName" type="myType" />
    <element name="hisName" type="hisType" />
    <element name="yourName" type="yourType" />
  </elements>
  </root>

最佳答案

要使您的集合元素能够直接位于父元素(而不是子集合元素)中,您需要重新定义您的 ConfigurationProperty。例如,假设我有一个集合元素,例如:

public class TestConfigurationElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
    public string Name
    {
        get { return (string)this["name"]; }
    }
}

还有一个集合,例如:

[ConfigurationCollection(typeof(TestConfigurationElement), AddItemName = "test")]
public class TestConfigurationElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new TestConfigurationElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((TestConfigurationElement)element).Name;
    }
}

我需要将父部分/元素定义为:

public class TestConfigurationSection : ConfigurationSection
{
    [ConfigurationProperty("", IsDefaultCollection = true)]
    public TestConfigurationElementCollection Tests
    {
        get { return (TestConfigurationElementCollection)this[""]; }
    }
}

注意 [ConfigurationProperty("", IsDefaultCollection = true)] 属性。给它一个空名称,并将其设置为默认集合允许我定义我的配置,如:

<testConfig>
  <test name="One" />
  <test name="Two" />
</testConfig>

代替:

<testConfig>
  <tests>
    <test name="One" />
    <test name="Two" />
  </tests>
</testConfig>

关于c# - 如何从 App.config 中读取这个自定义配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6218607/

相关文章:

c# - 格式化导航栏颜色并在 Razor 中添加分隔线

c# - Mini-profiler 不显示 sql 查询的任何统计信息?

c# - 如何防止程序集在不使用时加载

.net - Asp.Net 4.0 中的 ViewStateMode 属性

asp.net - 如何防止许多asp.net开发iis被打开?

c# - 在 C# 中迁移自定义 ConfigSection

java - 自定义配置文件 - Play !框架2.0

c# - UTF-8 文件数据到 ASCII

c# - Silverlight:在何处存储跨页面使用的数据

java - TestNG:如何以编程方式运行自定义 TestNG.XML 文件