我使用下面的代码来序列化一个类。
public static string SerializeToString<T>(this T toSerialize)
{
XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());
using (StringWriter textWriter = new StringWriter())
{
serializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
此代码间歇性地工作。有时它返回序列化字符串,有时不返回。任何地方都不例外。
我错过了什么吗?
答案 0 :(得分:3)
在致电StringWriter
之前,您需要Flush ToString()
:
public static string SerializeToString<T>(this T toSerialize)
{
XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());
using (StringWriter textWriter = new StringWriter())
{
serializer.Serialize(textWriter, toSerialize);
textWriter.Flush();
return textWriter.ToString();
}
}
当数据写入StringWriter
时,它首先被写入内部缓冲区。调用ToString()
时无法识别内部缓冲区中的数据。
或者,您可以使用以下代码:
public static string SerializeToString<T>(this T toSerialize)
{
XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());
StringBuilder stringBuilder = new StringBuilder();
using (StringWriter textWriter = new StringWriter(stringBuilder))
{
serializer.Serialize(textWriter, toSerialize);
}
return stringBuilder.ToString();
}
此处StringWriter
将其数据写入StringBuilder
。通过使用using
关键字,StringWriter
在离开块时自动关闭,迫使StringWriter
将其数据刷新到给定的StringBuilder
。