我正在为即将到来的项目尝试使用protobuf-net,但是我很难确定如何序列化一个类的列表。我创建了一个dotnet小提琴,以测试一些基本情况,并且一切正常,直到创建一个简单的类并将该类的列表添加到要序列化的另一个类中为止。我创建了一个类的实例并打印以显示所有值,然后进行序列化,反序列化并再次打印以显示所有数据均通过该过程完成,但我的列表一直保持空白。有人知道这是怎么回事吗?
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections.Generic;
using ProtoBuf;
using ProtoBuf.Meta;
public class Program
{
public static void Main()
{
var item = new MyClass();
var listItem1 = new ComplexList();
listItem1.pubField = "first one";
var listItem2 = new ComplexList();
listItem2.pubField = "second one";
item.ComplexList.Add(listItem1);
item.ComplexList.Add(listItem2);
item.Print();
Console.WriteLine();
Console.WriteLine();
var serialized = ProtoObjectToByteArray(item);
var deserialized = ProtoByteArrayToObject<MyClass>(serialized);
deserialized.Print();
}
public static byte[] ProtoObjectToByteArray(object obj)
{
if(obj == null)
return null;
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, obj);
return ms.ToArray();
}
}
public static T ProtoByteArrayToObject<T>(byte[] arrBytes)
{
if(arrBytes == null)
return default(T);
using (MemoryStream ms = new MemoryStream(arrBytes))
{
return Serializer.Deserialize<T>(ms);
}
}
}
[Serializable, ProtoContract]
public class ComplexList {
public string pubField;
public ComplexList(){}
}
[Serializable, ProtoContract]
public class MyClass {
public List<ComplexList> ComplexList { get; set; }
public MyClass(){
ComplexList = new List<ComplexList>();
}
public void Print(){
foreach(var x in ComplexList){
Console.WriteLine(x.pubField);
}
}
}
答案 0 :(得分:3)
Protobuf-net希望您注释您的类型:
[Serializable, ProtoContract]
public class ComplexList {
[ProtoMember(1)]
public string pubField;
public ComplexList(){}
}
[Serializable, ProtoContract]
public class MyClass {
[ProtoMember(1)]
public List<ComplexList> ComplexList { get; set; }
public MyClass(){
ComplexList = new List<ComplexList>();
}
public void Print(){
foreach(var x in ComplexList){
Console.WriteLine(x.pubField);
}
}
}
protobuf中的字段被赋予数字标识符,并且它需要一种可靠的方式来知道哪个字段是哪个数字。
请注意,protobuf-net不需要[Serializable]
。