C# 序列化自定义配置
我需要一些帮助来实现序列化自定义配置的方法。我从以下示例的内容开始: 读取配置工作正常,但无法保存对某些配置属性的修改(例如,更改属性P1以包含另一个字符串)。虽然调试不同对象的内容看起来很好(部分包含集合,其中包含三个代理项,其本身包含父类的实例)。已更改的项(P1=“”)的isModified标志设置为true(如预期) 调用config.Save()时会出现一些奇怪的行为,经过三天的调查(甚至是Microsoft基类),我无法找到问题所在。以下是我的一些结论: 我为每个SerializeX方法(SerializeSection、SerializeElement和SerializeToXmlElement)添加了一个覆盖,并逐步消除代码中的错误C# 序列化自定义配置,c#,xml-serialization,custom-configuration,C#,Xml Serialization,Custom Configuration,我需要一些帮助来实现序列化自定义配置的方法。我从以下示例的内容开始: 读取配置工作正常,但无法保存对某些配置属性的修改(例如,更改属性P1以包含另一个字符串)。虽然调试不同对象的内容看起来很好(部分包含集合,其中包含三个代理项,其本身包含父类的实例)。已更改的项(P1=“”)的isModified标志设置为true(如预期) 调用config.Save()时会出现一些奇怪的行为,经过三天的调查(甚至是Microsoft基类),我无法找到问题所在。以下是我的一些结论: 我为每个SerializeX
- SerializeSection是使用参数parentElement调用的(如预期的那样),该参数不是我想要序列化的节,因为集合属性是空的(我希望它具有作为配置文件一部分的三个实例)。使用此元素而不是parentElement调用base.SerializeSection可以解决此问题
- SerializeToXmlElement在SerializeElement之前调用,并且确实包含XmlWriter的实例(如预期的那样)
- SerializeElement在SerializeToXmlElement之后调用,并且不再包含XmlWriter的实例
- 当输入集合对象的序列化方法时,我希望集合的三个元素是序列化的。但是集合只包含一个新初始化的项,因此父属性返回null,而不是三个项
你好,Stefi这终于对我起作用了。也许它能帮助其他有同样问题的人。我将发布完整的代码以保持简单。这可能不是一流的解决方案,但它正在发挥作用。如果其他人能看一下并提出更好的方法,我将不胜感激 这篇文章帮助我实现了这一目标: 我的代码缺少元素集合(请参阅ThingElement.cs) thing.config
<configuration>
<configSections>
<section name="ExampleSection" type="ConsoleApplication1.Things.ExampleSection, ConsoleApplication1" />
</configSections>
<ExampleSection>
<things>
<thing type="one" name="one-1" color="green" />
<thing type="one" name="one-2" color="red" />
<thing type="two" name="two-1" />
</things>
</ExampleSection>
</configuration>
ExampleThingElementCollection.cs
[ConfigurationCollection(typeof(ThingElement), AddItemName = "thing",
CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class ExampleThingElementCollection : ConfigurationElementCollection
{
#region Constructors
public ExampleThingElementCollection()
{
}
#endregion
#region Properties
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
protected override string ElementName
{
get { return "thing"; }
}
#endregion
#region Indexers
public ThingElement this[int index]
{
get { return (ThingElement)base.BaseGet(index); }
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
base.BaseAdd(index, value);
}
}
new public ThingElement this[string name]
{
get { return (ThingElement)base.BaseGet(name); }
}
#endregion
#region Overrides
protected override ConfigurationElement CreateNewElement()
{
return new ThingElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return (element as ThingElement).Name;
}
#endregion
#region Methods
public void Add(ThingElement thing)
{
base.BaseAdd(thing);
}
public void Remove(string name)
{
base.BaseRemove(name);
}
public void Remove(ThingElement thing)
{
base.BaseRemove(GetElementKey(thing));
}
public void Clear()
{
base.BaseClear();
}
public void RemoveAt(int index)
{
base.BaseRemoveAt(index);
}
public string GetKey(int index)
{
return (string)base.BaseGetKey(index);
}
#endregion
}
ThingElement.cs(此类充当代理元素)
One.cs(父类,例如基类,如果您有其他派生
public class SpecialThing : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string)this["name"];
}
set
{
this["name"] = value;
}
}
[ConfigurationProperty("type", IsRequired = true)]
public string Type
{
get
{
return (string)this["type"];
}
set
{
this["type"] = value;
}
}
public virtual bool ProxySerializeElement(XmlWriter writer, bool serializeCollectionKey)
{
return SerializeElement(writer, serializeCollectionKey);
}
public void ProxyDeserializeElement(XmlReader reader, bool serializeCollectionKey)
{
DeserializeElement(reader, serializeCollectionKey);
}
}
public class One : SpecialThing
{
public One() { }
public One(string name, string type, string color)
{
base.Name = name;
base.Type = type;
Color = color;
}
[ConfigurationProperty("color")]
public string Color
{
get { return (string)this["color"]; }
set { this["color"] = value; }
}
}
2.C
public class Two : SpecialThing
{
public Two() { }
public Two(string name, string type)
{
base.Name = name;
base.Type = type;
}
}
有人有主意吗?
public class ThingElement : ConfigurationElement
{
#region Constructors
/// <summary>
/// Predefines the valid properties and prepares
/// the property collection.
/// </summary>
static ThingElement()
{
// Predefine properties here
s_propName = new ConfigurationProperty(
"name",
typeof(string),
null,
ConfigurationPropertyOptions.IsRequired
);
}
#endregion
#region Static Fields
private static ConfigurationProperty s_propName;
private static Dictionary<string, SpecialThing> elements = new Dictionary<string, SpecialThing>();
#endregion
#region Properties
/// <summary>
/// Gets the Name setting.
/// </summary>
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return (string)base[s_propName]; }
}
public SpecialThing Thing { get { return elements[Name]; } }
protected override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey)
{
return Thing.ProxySerializeElement(writer, serializeCollectionKey);
}
protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
{
SpecialThing obj = null;
string name = reader.GetAttribute("name");
string type = reader.GetAttribute("type");
switch (type)
{
case "one":
obj = new One();
break;
case "two":
obj = new Two();
break;
default:
throw new ArgumentException(string.Format("Invalid type: {0}", type));
}
base[s_propName] = name;
if (!elements.ContainsKey(name))
elements.Add(name, obj);
obj.ProxyDeserializeElement(reader, serializeCollectionKey);
}
private Hashtable attributes;
public Hashtable Attributes
{
get
{
if (attributes == null)
attributes = new Hashtable(StringComparer.OrdinalIgnoreCase);
return attributes;
}
}
protected override bool OnDeserializeUnrecognizedAttribute(String name, String value)
{
Attributes.Add(name, value);
return true;
}
protected override void PreSerialize(XmlWriter writer)
{
if (attributes != null)
{
IDictionaryEnumerator e = attributes.GetEnumerator();
while (e.MoveNext())
{
string xmlValue = (string)e.Value;
string xmlName = (string)e.Key;
if ((xmlValue != null) && (writer != null))
{
writer.WriteAttributeString(xmlName, xmlValue);
}
}
}
}
#endregion
}
public class SpecialThing : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string)this["name"];
}
set
{
this["name"] = value;
}
}
[ConfigurationProperty("type", IsRequired = true)]
public string Type
{
get
{
return (string)this["type"];
}
set
{
this["type"] = value;
}
}
public virtual bool ProxySerializeElement(XmlWriter writer, bool serializeCollectionKey)
{
return SerializeElement(writer, serializeCollectionKey);
}
public void ProxyDeserializeElement(XmlReader reader, bool serializeCollectionKey)
{
DeserializeElement(reader, serializeCollectionKey);
}
}
public class One : SpecialThing
{
public One() { }
public One(string name, string type, string color)
{
base.Name = name;
base.Type = type;
Color = color;
}
[ConfigurationProperty("color")]
public string Color
{
get { return (string)this["color"]; }
set { this["color"] = value; }
}
}
public class Two : SpecialThing
{
public Two() { }
public Two(string name, string type)
{
base.Name = name;
base.Type = type;
}
}