You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 4.7应用如何在App.config中引用自定义配置元素?

如何在.NET 4.7中配置并使用多个自定义配置元素

我来帮你搞定这个自定义配置的问题,结合你提到的项目结构(./ConfigurationItems/Children/Child),我给你一套完整的实现方案,从配置类的正确定义到App.config的配置,再到代码读取,一步到位。

1. 配置类的正确定义

首先得在ConfigurationItems/Children目录下创建对应的配置类,这些类需要继承.NET配置系统的基类:

Child元素类(单个配置项)

这个类对应你App.config里的<Child>节点:

using System.Configuration;

// 注意命名空间要和你的项目结构对应
namespace YourProjectName.ConfigurationItems.Children
{
    public class Child : ConfigurationElement
    {
        // 配置"name"属性,必填
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }

        // 配置"age"属性,可选,默认值0
        [ConfigurationProperty("age", IsRequired = false, DefaultValue = 0)]
        public int Age
        {
            get { return (int)this["age"]; }
            set { this["age"] = value; }
        }
    }
}

Child集合类(多个Child元素的容器)

这个类用来包裹多个<Child>节点,继承ConfigurationElementCollection:

using System.Configuration;

namespace YourProjectName.ConfigurationItems.Children
{
    // 指定集合元素类型为Child,添加元素时的节点名是"Child"
    [ConfigurationCollection(typeof(Child), AddItemName = "Child")]
    public class ChildCollection : ConfigurationElementCollection
    {
        // 创建新的Child元素
        protected override ConfigurationElement CreateNewElement()
        {
            return new Child();
        }

        // 返回元素的唯一键(这里用Child的Name属性)
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((Child)element).Name;
        }

        // 索引器:通过下标访问Child
        public Child this[int index]
        {
            get { return (Child)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        // 索引器:通过Name访问Child
        public new Child this[string name]
        {
            get { return (Child)BaseGet(name); }
        }
    }
}

配置节类(对应App.config里的<Children>节点)

这个类是整个自定义配置的入口,继承ConfigurationSection:

using System.Configuration;

namespace YourProjectName.ConfigurationItems.Children
{
    public class ChildrenSection : ConfigurationSection
    {
        // 配置默认集合,对应<Children>下的所有<Child>节点
        [ConfigurationProperty("", IsDefaultCollection = true)]
        public ChildCollection Children
        {
            get { return (ChildCollection)this[""]; }
            set { this[""] = value; }
        }
    }
}

2. App.config的正确配置

接下来要在App.config里注册这个自定义配置节,然后添加具体的配置内容。重点注意:配置节的type属性必须是完整的「命名空间+类名, 程序集名称」,程序集名称就是你的项目编译后的dll/exe名称(不带后缀)。

完整的App.config示例:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- 注册自定义配置节:替换YourProjectName和YourAssemblyName为你实际的命名空间和程序集名 -->
    <section name="Children" type="YourProjectName.ConfigurationItems.Children.ChildrenSection, YourAssemblyName" />
  </configSections>

  <!-- 自定义配置内容:添加多个<Child>节点 -->
  <Children>
    <Child name="Alice" age="25" />
    <Child name="Bob" age="30" />
    <Child name="Charlie" /> <!-- age会使用默认值0 -->
  </Children>

  <!-- .NET 4.7的默认启动配置 -->
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />
  </startup>
</configuration>

3. 在Program.cs中读取自定义配置

最后在主程序里读取配置的代码示例:

using System;
using YourProjectName.ConfigurationItems.Children;
using System.Configuration;

namespace YourProjectName
{
    class Program
    {
        static void Main(string[] args)
        {
            // 读取自定义配置节
            var childrenSection = ConfigurationManager.GetSection("Children") as ChildrenSection;

            if (childrenSection != null)
            {
                Console.WriteLine("读取到的子项列表:");
                foreach (Child child in childrenSection.Children)
                {
                    Console.WriteLine($"姓名:{child.Name},年龄:{child.Age}");
                }
            }
            else
            {
                Console.WriteLine("无法读取Children配置节,请检查App.config的配置是否正确!");
            }

            Console.ReadKey();
        }
    }
}

常见问题排查

  • 提示“无法识别的配置节Children”:检查configSections里的type属性是否正确,尤其是程序集名称和命名空间有没有写错,大小写要一致。
  • 配置属性不生效或抛出异常:检查配置类里的ConfigurationProperty特性的Name是否和App.config里的属性名一致;如果设置了IsRequired=true,必须在App.config里给该属性赋值。
  • 读取时返回null:确认ConfigurationManager.GetSection的参数和configSections里的name完全一致;如果配置类在类库项目中,配置文件要放在启动项目的App.config里,而不是类库的。

内容的提问来源于stack exchange,提问作者Some User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:29:33