c# - 自定义配置部分的问题

标签 c# app-config

我正在尝试制作一个相当简单的自定义配置部分。我的类(class)是:

namespace NetCenterUserImport
{
    public class ExcludedUserList : ConfigurationSection
    {
        [ConfigurationProperty("name")]
        public string Name
        {
            get { return (string)base["name"]; }
        }

        [ConfigurationProperty("excludedUser")]
        public ExcludedUser ExcludedUser
        {
            get { return (ExcludedUser)base["excludedUser"]; }
        }

        [ConfigurationProperty("excludedUsers")]
        public ExcludedUserCollection ExcludedUsers
        {
            get { return (ExcludedUserCollection)base["excludedUsers"]; }
        }
   }

   [ConfigurationCollection(typeof(ExcludedUser), AddItemName = "add")]
   public class ExcludedUserCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ExcludedUserCollection();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ExcludedUser)element).UserName;
        }
    }

    public class ExcludedUser : ConfigurationElement
    {
        [ConfigurationProperty("name")]
        public string UserName
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }
    }
}

我的app.config是:

  <excludedUserList name="test">
<excludedUser name="Hello" />
<excludedUsers>
  <add name="myUser" />
</excludedUsers>

当我尝试使用以下方式获取自定义配置部分时:

var excludedUsers = ConfigurationManager.GetSection("excludedUserList");

我收到一个异常消息

"Unrecognized attribute 'name'."

我确信我错过了一些简单的东西,但我已经看了这里的十几个示例和答案,似乎找不到我哪里出错了。

最佳答案

在 ExcludedUserCollection.CreateNewElement 方法中,您正在创建一个 ExcludedUserCollection 实例,它应该是单个元素,例如:

protected override ConfigurationElement CreateNewElement()
{
    return new ExcludedUser();
}

更改上述方法对我有用。

关于c# - 自定义配置部分的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32525415/

相关文章:

entity-framework - 到 Postgres 的连接字符串

c# - 在 Unity App.Config 文件中包含通用类

.net - 转换为 Visual Studio 2010/.Net 4.0 后的 app.config "Could not find schema information"

c# - VS2015 : Default Universal App template causes XAML designer crash

c# - Unity IOC - 如何根据自定义属性注册类型?

c# - 弹丸统一

c# - 签署 Windows 应用程序

c# - 在开发期间管理多个应用程序配置文件

asp.net - Web.config 和 App.config 的问题

c# - 使用System.Net.Mail.MailMessage时设置 "From"地址?