码迷,mamicode.com
首页 > Windows程序 > 详细

C# Protobuf序列化

时间:2020-08-24 16:59:11      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:类型   进制   summary   对象   namespace   tom   collect   cti   属性   

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

C# Protobuf序列化

标签:类型   进制   summary   对象   namespace   tom   collect   cti   属性   

原文地址:https://www.cnblogs.com/kexiong/p/13552327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!