问题
I am trying to serialize List<T>
but get empty file and List<T>
won't serialize. I do not get any exception and read protobuf-net manual, all members which I want to serialize are marked with [ProtoContract]
and [ProtoMember]
atributes
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:
protobuf-net does not look at static data; your main data is:
private static readonly List<T> ItemsList = new List<T>();
AFAIK, no serializer will look at that. Serializers are object-based; they are only interested in the values on an instance of an object. Beyond that, there is an issue of inheritance - you have not defined it for the model, so it is looking at each separately.
The following works fine, but frankly I suspect it would be wise to simplify the DTO model here; something as simple as a list of items should not involve 3 levels of hierarchy... in fact, it shouldn't involve any - List<T>
works just fine.
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; }
}
来源:https://stackoverflow.com/questions/13582208/protobuf-net-do-not-serialize-listt