我有以下方法将对象保存到文件:
// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
TextWriter textWriter = new StreamWriter(filename);
xmlSerializer.Serialize(textWriter, toSerialize);
textWriter.Close();
}
我承认我没有写它(我只是把它转换成一个带有类型参数的扩展方法)。
现在我需要它将 xml 作为字符串返回给我(而不是将其保存到文件中)。我正在研究它,但我还没有弄明白。
我认为这对于熟悉这些对象的人来说可能真的很容易。如果没有,我最终会弄清楚。
最佳答案
使用 StringWriter
而不是 StreamWriter
:
public static string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
using(StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
请注意,在 XmlSerializer 构造函数中使用 toSerialize.GetType()
而不是 typeof(T)
很重要:如果您使用第一个,则代码涵盖所有可能的T
的子类(对方法有效),而使用后者在传递从 T
派生的类型时会失败。
这是一个链接,其中包含一些激发此语句的示例代码,当使用 typeof(T)
时,XmlSerializer
会抛出 Exception
,因为您通过了派生类型的实例到调用在派生类型的基类中定义的 SerializeObject 的方法:http://ideone.com/1Z5J1 .
此外,Ideone 使用 Mono 来执行代码;使用 Microsoft .NET 运行时您将获得的实际 Exception
与 Ideone 上显示的Message
不同,但它仍然会失败。
关于c# - 将对象序列化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2434534/