2

我正在尝试序列化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; }
}
4

1 回答 1

2

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; }
}
于 2012-11-27T10:51:11.783 回答