我正在尝试制作一个相当简单的自定义配置部分。我的类(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/