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

2021-07-15 12:11

阅读:548

标签:反序列化   byte   数据   cep   XML   googl   ret   position   反序   

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

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

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

 

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

标签:反序列化   byte   数据   cep   XML   googl   ret   position   反序   

原文地址:https://www.cnblogs.com/liuxiaoji/p/9517635.html


评论


亲,登录后才可以留言!