【发布时间】:2013-06-13 15:32:53
【问题描述】:
我正在尝试删除一些旧的遗留引用,我现在正在做一些我以前从未尝试过的事情。假设我有一个这样的配置文件部分:
<customSection>
<customValues>
<custom key="foo" invert="True">
<value>100</value>
</custom>
<custom key="bar" invert="False">
<value>200</value>
</custom>
</customValues>
</customSection>
我现在创建了 ConfigurationSection、ConfigurationElement 和 ConfigurationElementCollection 类来正确读取所有这些内容。在这里它们供参考(基本上都是样板,除了 ValueElement 类,它覆盖了 Deserialize 方法以获取元素的值):
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("customValues")]
[ConfigurationCollection(typeof(CustomValueCollection), AddItemName = "custom")]
public CustomValueCollection CustomValues
{
get { return (CustomValueCollection)this["customValues"]; }
}
}
public class CustomValueCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new CustomElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((CustomElement) element).Key;
}
public CustomElement this[int index]
{
get { return (CustomElement) BaseGet(index); }
}
new public CustomElement this[string key]
{
get { return (CustomElement) BaseGet(key); }
}
public bool ContainsKey(string key)
{
var keys = new List<object>(BaseGetAllKeys());
return keys.Contains(key);
}
}
public class CustomElement : ConfigurationElement
{
[ConfigurationProperty("key", IsRequired = true)]
public string Key
{
get { return (string)this["key"]; }
}
[ConfigurationProperty("invert", IsRequired = true)]
public bool Invert
{
get { return (bool)this["invert"]; }
}
[ConfigurationProperty("value", IsRequired = true)]
public ValueElement Value
{
get { return (ValueElement)this["value"]; }
}
}
public class ValueElement : ConfigurationElement
{
private int value;
//used to get value of element, not of an attribute
protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey)
{
value = (int)reader.ReadElementContentAs(typeof(int), null);
}
public int Value
{
get { return value; }
}
}
我现在坚持的是这个业务需求:如果 CustomElement 的 Invert 值为 true,则在关联的 ValueElement 中反转 Value 属性的值。所以如果我访问“foo”下的“value”的值,我会得到-100。
有没有人知道如何将类似的东西传递给 ValueElement 对象或让 ValueElement 知道它的父 CustomElement 以便能够获取该 Invert 属性?我最初的想法是在 CustomElement 类的 Value 属性 getter 中进行检查,如果 Invert 为 true,则在那里修改 ValueElement 对象,但我对其他想法持开放态度。
这里的目标是在不触及配置文件的情况下删除遗留代码,否则我会将“value”子元素作为属性推送到父元素中。
谢谢
【问题讨论】:
-
附注,您的 xml 根元素不匹配 (customerSection, customSection)
-
谢谢,解决了这个问题,显然我刚刚为这个问题准备了一些东西 :)
标签: c# configuration custom-configuration