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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM