2012-11-27 34 views
2

我想序列化List<T>但獲取空文件和List<T>將不會序列化。我沒有得到任何的異常,並宣讀protobuf網手動,這是我想要序列的所有成員都標有[ProtoContract][ProtoMember] atributesprotobuf網不序列化列表<T>

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

回答

2

protobuf網不看靜態數據;你的主要數據是:

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

據我所知,沒有串行將着眼於這一點。串行器是基於對象的;他們只對對象實例的值感興趣。除此之外,還存在繼承問題 - 您尚未爲模型定義它,因此它正在分別查看每個模型。

以下工作正常,但坦率地說,我懷疑在這裏簡化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 = "[email protected]" }); 
      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); // [email protected] 
     } 
    } 
} 
[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; } 
}