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 = "打開的封口費"
        };
    }
}

 


免責聲明!

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



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