C# 使用 protobuf 进行对象序列化与反序列化

protobuf 是 google的一个开源项目,可用于以下两种用途:

(1)数据的存储(序列化和反序列化),类似于xml、json等;

(2)制作网络通信协议。

  源代码下载地址:https://github.com/mgravell/protobuf-net;

  开源项目地址如下:https://code.google.com/p/protobuf-net/。

protobuf 工具类 DataUtils.cs 代码如下:

nuget 包

Install-Package ServiceStack.ProtoBuf -Version 5.1.0
using System;
using System.IO;
using ProtoBuf;

namespace nugetdll
{
    public class DataUtils
    {
        public static byte[] ObjectToBytes<T>(T instance)
        {
            try
            {
                byte[] array;
                if (instance == null)
                {
                    array = new byte[0];
                }
                else
                {
                    MemoryStream memoryStream = new MemoryStream();
                    Serializer.Serialize(memoryStream, instance);
                    array = new byte[memoryStream.Length];
                    memoryStream.Position = 0L;
                    memoryStream.Read(array, 0, array.Length);
                    memoryStream.Dispose();
                }

                return array;

            }
            catch (Exception ex)
            {

                return new byte[0];
            }
        }

        public static T BytesToObject<T>(byte[] bytesData, int offset, int length)
        {
            if (bytesData.Length == 0)
            {
                return default(T);
            }
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                memoryStream.Write(bytesData, 0, bytesData.Length);
                memoryStream.Position = 0L;
                T result = Serializer.Deserialize<T>(memoryStream);
                memoryStream.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
    }

    [ProtoContract]
    public class Test
    {
        [ProtoMember(1)]
        public string S { get; set; }

        [ProtoMember(2)]
        public string Type { get; set; }

        [ProtoMember(3)]
        public int I { get; set; }

        /// <summary>
        /// 默认构造函数必须有,否则反序列化会报 No parameterless constructor found for x 错误!
        /// </summary>
        public Test() { }

        public static Test Data => new Test
        {
            I = 222,
            S = "xxxxxx",
            Type = "打开的封口费"
        };
    }
}

 

posted @ 2018-08-22 14:53  刘小吉  阅读(12440)  评论(0编辑  收藏  举报