C# Protobuf序列化

1 . 创建Protobuf序列化 工具类ProtobufExchang.cs, 需要添加应用protobuf-net.dll 组件

using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Protobuf序列化
{
public static class ProtobufExchang
{
/// <summary>
/// 使用protobuf把对象序列化为Byte数组
/// </summary>
/// <typeparam name="T">需要反序列化的对象类型,必须声明[ProtoContract]特征,且相应属性必须声明[ProtoMember(序号)]特征</typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static Byte[] ProtobufSerialize<T>(this T obj)
{
using (var memory = new MemoryStream())
{
Serializer.Serialize(memory, obj);
return memory.ToArray();
}
}

/// <summary>
/// 使用protobuf反序列化二进制数组为对象
/// </summary>
/// <typeparam name="T">需要反序列化的对象类型,必须声明[ProtoContract]特征,且相应属性必须声明[ProtoMember(序号)]特征</typeparam>
/// <param name="data"></param>
public static T ProtobufDeserialize<T>(this Byte[] data)
{
using (var memory = new MemoryStream(data))
{
return Serializer.Deserialize<T>(memory);
}
}
}
}

2 . 创建需要序列化的实体类StudentEntity.cs, 特别提醒被序列的对象需要打上标记[ProtoContract]

using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Protobuf序列化StudentEntity
{
[Serializable]
[ProtoContract]
public class StudentEntity
{
/// <summary>
/// 姓名
/// </summary>
[ProtoMember(1)]
public string Name { get; set; }

/// <summary>
/// ming
/// </summary>
[ProtoMember(2)]
public int Age { get; set; }
}
}

3 . 演示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Protobuf序列化
{
class Program
{
static void Main(string[] args)
{
StudentEntity st = new StudentEntity() { Name = "aaaa", Age = 12 };

List<StudentEntity> list = new List<StudentEntity>()
{
new StudentEntity(){Name = "qqq",Age = 13},
new StudentEntity(){Name = "qqq1",Age = 14},
new StudentEntity(){Name = "qqq2",Age = 15},
new StudentEntity(){Name = "qqq3",Age = 16}

};
// var aa = ProtobufExchang.ProtobufSerialize<StudentEntity>(st)
//var aa = st.ProtobufSerialize();
var aa = ProtobufExchang.ProtobufSerialize(list);
var ss = ProtobufExchang.ProtobufDeserialize<List<StudentEntity>>(aa);
foreach (var item in ss)
{
Console.WriteLine(item.Name+"/"+item.Age);
}

StudentEntity e = null;
var www = ProtobufExchang.ProtobufSerialize(e);
var sss = www.ProtobufDeserialize<StudentEntity>();
Console.Read();
}
}
}

相关文章