自定义配置部分的问题
本文关键字:问题 配置部 自定义 | 更新日期: 2023-09-27 18:12:25
我试图做一个相当简单的自定义配置部分。我的班级是:
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");
我得到一个异常说
"无法识别的属性'name'。"
我肯定我错过了一些简单的东西,但是我已经看了这里的一打例子和答案,似乎找不到我错在哪里。
In ExcludedUserCollection。如果您正在创建一个ExcludedUserCollection实例,则它应该是单个元素,例如:
protected override ConfigurationElement CreateNewElement()
{
return new ExcludedUser();
}
改变上面的方法对我有效