[英]Serializing derived class to XML
I'm trying to serialize a derived class and serialize both the derived's properties and the base's properties. 我正在尝试序列化派生的类,并序列化派生的属性和基本属性。 Right now derived properties are serialized, but base properties are not.
现在,派生的属性已序列化,但基本属性尚未序列化。 What am I missing?
我想念什么? Both the base and derived types are marked [Serializable].
基本类型和派生类型都标记为[可序列化]。
String SaveBody<T>(String bodyFile, T body) where T : FreeBody
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var xmlStream = new MemoryStream())
using (TextWriter fileStream = new StreamWriter(xmlStream))
{
serializer.Serialize(fileStream, body);
fileStream.Flush();
xmlStream.Seek(0, SeekOrigin.Begin);
String text = new StreamReader(xmlStream).ReadToEnd();
File.WriteAllText(bodyFile, text);
return text;
}
}
I was mistaken in the problem. 我在这个问题上弄错了。 The properties not being serialized had been null/empty, so the serializer didn't output them.
未序列化的属性为空/空,因此序列化器未输出它们。 Initializing those properties to defaults created the behavior I expected.
将这些属性初始化为默认值将创建我期望的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.