代码很简单直接上了
using ProtoBuf;
using UnityEngine;
using System.IO;
using System;
public class Test2 : MonoBehaviour
{
private void Start()
{
NetModel item = new NetModel()
{
ID = 1,
Commit = "LZ",
Message = "Unity"
};
byte[] result = Serialize<NetModel>(item);
NetModel backIns = DeSerialize<NetModel>(result);
Debug.Log(backIns.ID);
Debug.Log(backIns.Commit);
Debug.Log(backIns.Message);
}
public byte[] Serialize<T>(T classValue)
{
try
{
using (MemoryStream memory = new MemoryStream())
{
Serializer.Serialize<T>(memory, classValue);
byte[] result = new byte[memory.Length];
memory.Position = 0;
memory.Read(result, 0, result.Length);
return result;
}
}
catch (Exception e)
{
Debug.Log(e);
return null;
}
}
public T DeSerialize<T>(byte[] value) //where T : class // 这里可以做个约束class类型, 也可以做个基佬,让所有序列化类继承之再去约束这个类更安全
{
try
{
using (MemoryStream ms = new MemoryStream())
{
ms.Write(value, 0, value.Length);
ms.Position = 0;
return Serializer.Deserialize<T>(ms);
}
}
catch(Exception e)
{
Debug.Log("Error:"+e);
return default(T);
}
}
[ProtoContract]
public class NetModel
{
[ProtoMember(1)]
public int ID;
[ProtoMember(2)]
public string Commit;
[ProtoMember(3)]
public string Message;
}
}