自定义配置部分

时间:2015-09-11 14:05:14

标签: c# app-config

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

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");

我得到一个例外

  

“无法识别的属性'名称'。”

我确定我错过了一些简单的东西,但我已经在这里查看了十几个例子和答案,似乎无法找到我出错的地方。

1 个答案:

答案 0 :(得分:2)

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

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

更改上述方法对我有用。

相关问题