繁体   English   中英

protobuf-net 不序列化列表<T>

[英]protobuf-net do not serialize List<T>

我正在尝试序列化List<T>但得到空文件并且List<T>不会序列化。 我没有得到任何异常并阅读 protobuf-net 手册,我想序列化的所有成员都标有[ProtoContract][ProtoMember]属性

public void Save()
{
    using (var outputStream = File.Create(SettingsModel.QueueListDataFile))
    {      
        Serializer.Serialize(outputStream, QueueList);
    }
}

[Serializable]
[ProtoContract]
public class QueueList : SafeList<QueueItem>
{

}

[Serializable]    
[ProtoContract]
public class SafeList<T> : SafeLock
{
    [ProtoMember(1)]
    private static readonly List<T> ItemsList = new List<T>();
}

[Serializable]
[ProtoContract]
public class QueueItem
{
    [ProtoMember(1)]
    public string SessionId { get; set; }
    [ProtoMember(2)]
    public string Email { get; set; }
    [ProtoMember(3)]
    public string Ip { get; set; }
}

protobuf-net 不查看静态数据; 您的主要数据是:

private static readonly List<T> ItemsList = new List<T>();

AFAIK,没有序列化程序会查看它。 序列化程序是基于对象的; 他们只对对象实例上的值感兴趣。 除此之外,还有一个继承问题——你没有为模型定义它,所以它会分别查看每个。

以下工作正常,但坦率地说,我怀疑在这里简化 DTO 模型是明智的; 像项目列表这样简单的东西不应该涉及 3 个层次结构......事实上,它不应该涉及任何- List<T>工作得很好


using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
static class Program
{
    public static void Main()
    {
        using (var outputStream = File.Create("foo.bin"))
        {
            var obj = new QueueList { };
            obj.ItemsList.Add(new QueueItem { Email = "hi@world.com" });
            Serializer.Serialize(outputStream, obj);
        }
        using (var inputStream = File.OpenRead("foo.bin"))
        {
            var obj = Serializer.Deserialize<QueueList>(inputStream);
            Console.WriteLine(obj.ItemsList.Count); // 1
            Console.WriteLine(obj.ItemsList[0].Email); // hi@world.com
        }
    }
}
[Serializable]
[ProtoContract]
public class QueueList : SafeList<QueueItem>
{

}

[ProtoContract]
[ProtoInclude(1, typeof(SafeList<QueueItem>))]
public class SafeLock {}

[Serializable]
[ProtoContract]
[ProtoInclude(2, typeof(QueueList))]
public class SafeList<T> : SafeLock
{
    [ProtoMember(1)]
    public readonly List<T> ItemsList = new List<T>();
}

[Serializable]
[ProtoContract]
public class QueueItem
{
    [ProtoMember(1)]
    public string SessionId { get; set; }
    [ProtoMember(2)]
    public string Email { get; set; }
    [ProtoMember(3)]
    public string Ip { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM