解决:以下代码没有像我想象的那样导致无限循环。循环在调用反序列化的代码中。这个发布的代码工作得很好
我正在尝试序列化和反序列化为xml以下对象
public class MessageObjectCollection : List<MessageObject>
{
public string Serialize()
{
return XmlObjectSerializer.SerializeObject(this);
}
public static MessageObjectCollection DeSerialize(string serializedPriceHistory)
{
return XmlObjectSerializer.DeserializeObject<MessageObjectCollection>(serializedPriceHistory);
}
}
MessageObject类看起来像这样
public class MessageObject
{
public string Title;
public MessageObjectCollection Responses;
}
所以如果我有一个messageobjectcollection的实例,它看起来像:
var msgColl = new MessageObjectCollection
{
new MessageObject
{
Title = "Hello",
Responses = new MessageObjectCollection
{
new MessageObject
{
Title = "hi",
Responses = null
}
}
}
}
我可以通过调用将其序列化 var xml = msgColl.Serialize();
然而,当我尝试通过调用反序列化时 var msgColl = new MessageObjectCollection()。Deserialize(xml);
我在反序列化方法中遇到了堆栈溢出异常:
public static T DeserializeObject<T>(string xml)
{
T result;
var ser = new XmlSerializer(typeof(T));
var buffer = StringToUTF8ByteArray(xml);
using (var stream = new MemoryStream(buffer, 0, buffer.Length))
{
result = (T) ser.Deserialize(stream);
}
return result;
}
任何人都知道我做错了什么?
答案 0 :(得分:0)
我不确定它是否与问题相关,但由于Deserialize方法是静态的,你不应该打电话......
var msgColl = MessageObjectCollection.Deserialize(xml);
而不是......
var msgColl = new MessageObjectCollection().Deserialize(xml);
...