• C#序列化和反序列化


    序列化和反序列化代码如下

      /// <summary>
        /// 将一个object对象序列化,返回一个byte[]
        /// </summary>
        public static byte[] ObjectToBytes(object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                return ms.GetBuffer();
            }
        }
    
        /// <summary>
        /// 将一个序列化后的byte[] 数组还原
        /// </summary>
        public static object BytesToObject(byte[] Bytes)
        {
            using (MemoryStream ms = new MemoryStream(Bytes))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(ms);
            }
        }

    测试代码如下

       void Start()
        {
            TestRequest request = new TestRequest(100,1, "测试", true);
            byte[] bytes = ObjectToBytes(request);
    
            Debug.LogError(bytes.Length);
    
            TestRequest testRequest = BytesToObject(bytes)  as TestRequest;
            if (testRequest == null)
            {
                Debug.LogError("反序列化对象为空");
                return;
            }
            Debug.LogError(testRequest.ToString());
        }

    测试序列化基类Request,需要加[Serializable]标签

    using System;
    
    
    [Serializable]
    public class Request
    {
        public int msgType;
    
        public string b;
    
        public bool c;
        public Request()
        {
    
        }
        public Request(int msgType, string b,bool c)
        {
            this.msgType = msgType;
            this.b = b;
            this.c = c;
        }
    
        public override string ToString()
        {
            return "Request[msgType:" + msgType + "b:" + b + "    c:" + c + "]";
        }
    }
    

      测试序列化类TestRequest,也需要加[Serializable]标签

    using System;


    [Serializable]
    public class TestRequest : Request
    {
        public int testNum;
        public TestRequest(int testNum, int msgType,string b,bool c):base(msgType,b,c)
        {
            this.testNum = testNum;
        }

        public override string ToString()
        {
            return "TestRequest[TestNum:"+testNum+" msgType:" + msgType + " b:" + b + "    c:" + c + "]";
        }
    }
  • 相关阅读:
    第07组 Beta冲刺(2/5)
    第07组 Beta冲刺(1/5)
    第07组 Alpha事后诸葛亮
    第07组 Alpha冲刺(5/6)
    第07组 Alpha冲刺(6/6)
    软工实践个人总结
    第01组 Beta版本演示
    第01组 Beta冲刺(5/5)
    第01组 Beta冲刺(4/5)
    第01组 Beta冲刺(3/5)
  • 原文地址:https://www.cnblogs.com/xiaobao2017/p/12760762.html
Copyright © 2020-2023  润新知