2015-09-11 107 views
2

我想做一个相当简单的自定义配置部分。我的班级:自定义配置部分的问题

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

'excludedUserList'是节的开始吗?如果是这样,我不认为你可以有一个属性附加到它。 – rbm

+0

那么不是真的 - 检查这里:http://stackoverflow.com/questions/9187523/adding-custom-attributes-to-custom-provider-configuration-section-in-app-config – rbm

+0

即使没有excludedUserList属性我得到同样的错误。我只添加了确定错误出现的时间。我向该部分添加了自定义属性,然后将该自定义属性添加到该部分,并且当这两者都工作时,将自定义集合添加回来,并且一切都再次破碎。 – DrewB

回答

2

在ExcludedUserCollection.CreateNewElement方法是创建一个ExcludedUserCollection情况下,它应该是一个单一的元素,如:

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

更改方法为我上面的工作。

+1

完美!谢谢。我知道这是我忽视的简单事情,但我办公室里唯一的其他开发人员中风了,所以我没有人像这种ATM那样同行评审。 – DrewB