序列化对象的字符串 [英] Serialize an object to string

查看:192
本文介绍了序列化对象的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法将一个对象保存到一个文件:

I have the following method to save an Object to a file:

// 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();
}

我承认我没有写它(我只是它转换成拿了类型参数的扩展方法)。

I confess I did not write it (I only converted it to a extension method that took a type parameter).

现在我需要它给XML还给我作为一个字符串(而不是将其保存到一个文件)。我寻找到它,但我还没有想通出来呢。

Now I need it to give the xml back to me as a string (rather than save it to a file). I am looking into it, but I have not figured it out yet.

我想这可能是很容易的人熟悉这些对象。如果没有,我会弄清楚最后。

I thought this might be really easy for someone familiar with these objects. If not I will figure it out eventually.

推荐答案

使用一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.io.stringwriter.aspx\"><$c$c>StringWriter代替<一href=\"http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx\"><$c$c>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();
    }
}

请注意,使用它是非常重要的 toSerialize.GetType()而不是的typeof(T)在XmlSerializer的构造:如果你使用的第一个code覆盖 T (这是有效的方法)的所有可能的子类,而使用后者会传递时失败从 T 派生类型。下面是一些例子code,它激励这一说法,与的XmlSerializer 抛出异常链接的typeof(T)被使用,因为你传递一个派生类型到在派生类的基类中定义调用SerializeObject的方法的一个实例:http://ideone.com/1Z5J1

Note, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible subclasses of T (which are valid for the method), while using the latter one will fail when passing a type derived from T.    Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject that is defined in the derived type's base class: http://ideone.com/1Z5J1.

此外,Ideone使用单声道执行code;实际例外你会得到使用Microsoft .NET运行时都有不同的消息比Ideone显示的,但它失败一样。

Also, Ideone uses Mono to execute code; the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

这篇关于序列化对象的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆