如何序列化为变量

时间:2012-02-07 21:47:15

标签: c# serialization

以下代码示例演示如何序列化/反序列化为文件。我怎么能修改它来序列化为变量而不是文件? (假设变量将传递给读/写方法而不是文件名)。

    public static void WriteObject(string fileName)
    {
        Console.WriteLine(
            "Creating a Person object and serializing it.");
        Person p1 = new Person("Zighetti", "Barbara", 101);
        FileStream writer = new FileStream(fileName, FileMode.Create);
        DataContractSerializer ser =
            new DataContractSerializer(typeof(Person));
        ser.WriteObject(writer, p1);
        writer.Close();
    }

    public static void ReadObject(string fileName)
    {
        Console.WriteLine("Deserializing an instance of the object.");
        FileStream fs = new FileStream(fileName,
        FileMode.Open);
        XmlDictionaryReader reader =
            XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
        DataContractSerializer ser = new DataContractSerializer(typeof(Person));

        // Deserialize the data and read it from the instance.
        Person deserializedPerson =
            (Person)ser.ReadObject(reader, true);
        reader.Close();
        fs.Close();
        Console.WriteLine(String.Format("{0} {1}, ID: {2}",
        deserializedPerson.FirstName, deserializedPerson.LastName,
        deserializedPerson.ID));
    }

1 个答案:

答案 0 :(得分:8)

您可以将FileStream更改为内存流并将其转储到byte[]

public static byte[] WriteObject<T>(T thingToSave)
{
    Console.WriteLine("Serializing an instance of the object.");
    byte[] bytes;
    using(var stream = new MemoryStream())
    {
        var serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(stream, thingToSave);
        bytes = new byte[stream.Length];
        stream.Position = 0;
        stream.Read(bytes, 0, (int)stream.Length);
    }
    return bytes;

}

public static T ReadObject<T>(byte[] data)
{
    Console.WriteLine("Deserializing an instance of the object.");

    T deserializedThing = default(T);

    using(var stream = new MemoryStream(data))
    using(var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
    {
        var serializer = new DataContractSerializer(typeof(T));

        // Deserialize the data and read it from the instance.
        deserializedThing = (T)serializer.ReadObject(reader, true);
    }
    return deserializedThing;
}