如何在后代元素上使用 .NET 自定义 ConfigurationElement 属性?
如何获取并使用后代 CustomSetting 元素中父 ConfigurationSection 中设置的属性?当 CustomSetting 元素返回 Value 属性时,我需要此属性。
我想像这样格式化 App.config:
<CustomSettings someProperty="foo">
<CustomSetting key="bar" value="fermeneba" />
<CustomSetting key="laa" value="jubaduba" />
</CustomSettings>
我的代码可以正常工作,只是我无法找到从 CustomSetting 类访问 someProperty 属性的方法。到目前为止,我发现的唯一方法就是像这样格式化配置,这很混乱:
<CustomSettings>
<CustomSetting someProperty="foo" key="bar" value="fermeneba" />
<CustomSetting someProperty="foo" key="laa" value="jubaduba" />
</CustomSettings>
How can I get and use an attribute set in the parent ConfigurationSection in the descendent CustomSetting element? I need this attribute when the CustomSetting element is returning the Value property.
I want to format the App.config like this:
<CustomSettings someProperty="foo">
<CustomSetting key="bar" value="fermeneba" />
<CustomSetting key="laa" value="jubaduba" />
</CustomSettings>
I have the code working, except that I cannot find a way to access the someProperty attribute from the CustomSetting class. The only way that I've found, so far, is to format the configuration like this, which is messy:
<CustomSettings>
<CustomSetting someProperty="foo" key="bar" value="fermeneba" />
<CustomSetting someProperty="foo" key="laa" value="jubaduba" />
</CustomSettings>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现这一点比应有的要困难,因为 System.Configuration API 不允许您从
ConfigurationElement
导航到其父级。因此,如果您想访问父元素上的某些信息,则需要手动创建该关系。我已经整理了一个示例实现,可以为您问题中的配置片段执行此操作:您可以看到
CustomSettingElementCollection
有一个Section
属性,该属性在该部分的 <代码>元素 getter。反过来,CustomSettingElement
具有一个Parent
属性,该属性在集合的CreateNewElement()
方法中设置。这样就可以沿着关系树往上走,并向元素添加
SomeProperty
属性,即使该属性与该元素上的实际 ConfigurationProperty 并不对应。希望这能让您了解如何解决您的问题!
Achieving this is more difficult than it should be since the System.Configuration API doesn't allow you to navigate from a
ConfigurationElement
to its parent. Hence, if you want to access some information that on a parent element you need to create that relationship manually. I've put together a sample implementation that does that for the config snippet in your question:You can see that the
CustomSettingElementCollection
has aSection
property which gets set in the section'sElements
getter. TheCustomSettingElement
, in turn, has aParent
property which gets set in the collection'sCreateNewElement()
method.That then makes it possible to walk up the relationship tree and to add a
SomeProperty
property to the element even though this one doesn't correspond to an actual ConfigurationProperty on that element.Hope that gives you an idea how to solve your problem!