【发布时间】:2025-12-20 05:05:07
【问题描述】:
我为我的 app.config 创建了一个自定义的 ConfigurationSection、ConfigurationElement(s) 和 ConfigurationElementCollection(s),它基于 this documentation。
现在我希望能够访问任何配置元素中的父元素。
例如以下几行:
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("child")]
public ChildElement Child
{
get { return (ChildElement)this["child"]; }
set { this["child"] = value; }
}
}
public class ChildElement : ConfigurationElement
{
[ConfigurationProperty("name")]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("nestedchild")]
public NestedChildElement NestedChild
{
get { return (NestedChildElement)this["nestedchild"]; }
set { this["nestedchild"] = value; }
}
}
public class NestedChildElement : ConfigurationElement
{
[ConfigurationProperty("name")]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
public void Sample()
{
// How can I access parent ChildElement object
// and also its parent CustomSection object from here?
}
}
ConfigurationElement 基类中是否有一些我缺少的东西可以让我做到这一点?
我希望是否可以通过某种通用解决方案来实现这一目标;
不需要在每个元素上引入类似 Parent 属性的东西,然后需要在每个 ConfigurationProperty getter 中分配该属性值。
【问题讨论】:
-
“ChildElement”类不是“NestedChildElement”类的父类。
-
请注意,“ChildElement”包含“ConfigurationProperty”或“NestedChildElement”。在“app.config”中,这是一个“嵌套子”XML 元素,它是“子”XML 元素的父元素。我希望这能说明问题。
标签: c# app-config configurationsection configurationelement