3

我有我能想到的最通用的序列化示例:一个有两个变量和一个实例的类,我想序列化。但是我有一个问题,下面的代码总是给我一个空字符串。我想不出为什么会这样..

    public static async void SaveState()
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(new Deck().GetType());

        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, new Deck());
            using (var sr = new StreamReader(stream))
            {
                Debug.WriteLine(sr sr.ReadToEnd());
            }
        }      
    }




[DataContract]
class Deck
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public int Points { get; set; } = 1500;


    public Deck()
    {
        this.Name = "Deck Name";
    }
}
4

1 回答 1

6

因为你的流在最后。将您的代码更改为:

public static void Main (string[] args)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(new Deck().GetType());

            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, new Deck());
                stream.Position = 0;//the key.
                using (var sr = new StreamReader(stream))
                {
                    Console.WriteLine(sr.ReadToEnd());
                }
            }
        }
于 2016-09-19T16:52:32.493 回答