實現這點比較難比它應該是,因爲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
具有獲取部分的Elements
吸氣設置Section
屬性。反過來,CustomSettingElement
有一個Parent
屬性,該屬性在集合的CreateNewElement()
方法中設置。
然後,可以遍歷關係樹並向該元素添加一個SomeProperty
屬性,即使該屬性不對應於該元素上的實際ConfigurationProperty。
希望能給你一個想法如何解決你的問題!
這工作完美!謝謝! –