木骰

关于protobuf-net非泛型的正反序列化

有时候会想用非泛型的方式正反序列化,非泛型的serialize和deserialize在Serializer.NonGeneric下。


usingProtoBuf;
using System;
using System.IO;
using UnityEngine;

public class Serialize  {

                 /// 
    /// 序列化一个对象
    /// 
    /// 
    /// 
    /// 
    public static byte [] serialize(T obj)
    {
        try
        {
            byte[] buffer = null ;
            MemoryStream ms = new MemoryStream();
            Serializer.Serialize(ms, obj);
            buffer = ms.ToArray();
            ms.Close();
            return buffer;
        }
        catch (Exception e)
        {
            Debug.LogError("serialize err:" + e.Message);
        }
        return null ;
    }

    /// 
    /// 反序列化一个字节流
    /// 
    /// 
    /// 
    /// 
    public static T deserialize(byte[]buffer)
    {
        try
        {
            MemoryStream ms = new MemoryStream(buffer);
            T obj = Serializer .Deserialize(ms);
            return obj;
        }
        catch (Exception e)
        {
            Debug.LogError("deserialize err:" + e.Message);
        }
        return default (T);
    }

    public static object deserialize(byte[]buffer, Type type)
    {
        try
        {
            MemoryStream ms = new MemoryStream(buffer);
            object obj= Serializer .NonGeneric.Deserialize(type, ms);
            return obj;
        }
        catch (Exception e)
        {
            Debug.LogError("deserialize err:" + e.Message);
        }
        return null ;
    }
}
— 于 共写了876个字
— 文内使用到的标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*