protobuf-net不序列化List <t> </t>

时间:2012-11-27 10:29:54

标签: c# protobuf-net

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

1 个答案:

答案 0 :(得分: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; }
}