gpt4 book ai didi

c# - 使用数据契约的空字符串序列化

转载 作者:行者123 更新时间:2023-12-02 07:53:29 25 4
gpt4 key购买 nike

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

    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";
}
}

最佳答案

因为您的直播已结束。将代码更改为:

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

关于c# - 使用数据契约的空字符串序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com