【问题标题】:Problems with custom config section自定义配置部分的问题
【发布时间】:2015-09-11 14:05:13
【问题描述】:

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

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

我得到一个异常提示

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

我确定我遗漏了一些简单的东西,但我在这里查看了十几个示例和答案,似乎无法找到我要去哪里。

【问题讨论】:

  • excludedUserList 是该部分的开头吗?如果是这样,我认为您不能附加一个属性。
  • 不是真的 - 在这里查看:stackoverflow.com/questions/9187523/…
  • 即使没有 excludeUserList 中的属性,我也会得到同样的错误。我只是添加以确定错误出现的确切时间。我向该部分添加了一个自定义属性,然后将自定义属性添加到该部分,当两者都起作用时,将自定义集合重新添加进去,一切都再次中断。

标签: c# app-config


【解决方案1】:

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

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

改变上述方法对我有用。

【讨论】:

  • 完美!谢谢你。我知道我忽略了一些简单的事情,但我办公室里唯一的其他开发人员中风了,所以我没有人可以对这台 ATM 之类的东西进行同行评审。
猜你喜欢
  • 2011-05-25
  • 1970-01-01
  • 2010-10-25
  • 2011-02-28
  • 2010-11-12
  • 2013-09-17
  • 2011-07-04
  • 2012-12-12
相关资源
最近更新 更多