ConfigurationElement
System.Configuration APIでは、からその親に移動できないため、これを達成することは本来よりも困難です。したがって、親要素でその関係を手動で作成する必要がある情報にアクセスする場合。私はあなたの質問の構成スニペットのためにそれを行うサンプル実装をまとめました:
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
CustomSettingElement
Parent
CreateNewElement()
これにより、関係ツリーをたどりSomeProperty
、要素の実際のConfigurationPropertyに対応していなくても、要素にプロパティを追加することができます。
それがあなたの問題を解決する方法のアイデアをあなたに与えることを願っています!