如何获取并使用后代 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>
最佳答案
实现这一目标比应有的困难,因为 System.Configuration API 不允许您从 ConfigurationElement
导航到其父级。因此,如果您想访问父元素上的某些信息,则需要手动创建该关系。我已经整理了一个示例实现,可以为您问题中的配置片段执行此操作:
public class CustomSettingsSection : ConfigurationSection
{
[ConfigurationProperty("someProperty", DefaultValue="")]
public string SomeProperty
{
get { return (string)base["someProperty"]; }
set { base["someProperty"] = value; }
}
[ConfigurationProperty("", IsDefaultCollection = true)]
public CustomSettingElementCollection Elements
{
get
{
var elements = base[""] as CustomSettingElementCollection;
if (elements != null && elements.Section == null)
elements.Section = this;
return elements;
}
}
}
public class CustomSettingElementCollection : ConfigurationElementCollection
{
internal CustomSettingsSection Section { get; set; }
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
public CustomSettingElement this[string key]
{
get { return BaseGet(key) as CustomSettingElement; }
}
protected override ConfigurationElement CreateNewElement()
{
return new CustomSettingElement { Parent = this };
}
protected override object GetElementKey(ConfigurationElement element)
{
return (element as CustomSettingElement).Key;
}
protected override string ElementName
{
get { return "customSetting"; }
}
}
public class CustomSettingElement : ConfigurationElement
{
internal CustomSettingElementCollection Parent { get; set; }
public string SomeProperty
{
get
{
if (Parent != null && Parent.Section != null)
return Parent.Section.SomeProperty;
return default(string);
}
}
[ConfigurationProperty("key", IsKey = true, IsRequired = true)]
public string Key
{
get { return (string)base["key"]; }
set { base["key"] = value; }
}
[ConfigurationProperty("value", DefaultValue = "")]
public string Value
{
get { return (string)base["value"]; }
set { base["value"] = value; }
}
}
您可以看到 CustomSettingElementCollection
有一个 Section
属性,该属性在该部分的 Elements
getter 中设置。反过来,CustomSettingElement
有一个 Parent
属性,该属性在集合的 CreateNewElement()
方法中设置。
这样就可以沿着关系树向上走,并向元素添加 SomeProperty
属性,即使该属性与该元素上的实际 ConfigurationProperty 并不对应。
希望这能让您了解如何解决您的问题!
关于.net - 如何在后代元素上使用 .NET 自定义 ConfigurationElement 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7044871/