C# 使用 protobuf 進行對象序列化與反序列化

protobuf 是 google的一個開源項目,可用於如下兩種用途:git

(1)數據的存儲(序列化和反序列化),相似於xml、json等;github

(2)製做網絡通訊協議。json

  源代碼下載地址:https://github.com/mgravell/protobuf-net;網絡

  開源項目地址以下:https://code.google.com/p/protobuf-net/。less

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 = "打開的封口費"
        };
    }
}
相關文章
相關標籤/搜索