基于唐老狮网络TCP Socket BaseData类扩展 列表字典数组实现的序列化与反序列化二进制封装

原生的BaseData类只实现了基础的数据序列化方法,没有实现字典列表数组的序列化与反序列化,在后续学习过程中,个人手动扩展了剩余的方法,初次尝试如有错误请各位大佬帮我指点,谢谢!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEngine.XR;
 
public abstract class BaseData
{
    public abstract int GetID();
    public abstract int GetBytesNum();
    public abstract byte[] Writeing();
    /// <summary>
    /// 把2进制字数组反序列化到成员变量当中
    /// </summary>
    /// <param name="bytes">反序列化使用的字节数组</param>
    /// <param name="beginIndex">从该字节的第几个位置开始解析,默认0</param>
    /// <returns></returns>
    public abstract int Reading(byte[] bytes, int beginIndex = 0);
 
    /// <summary>
    /// 存储int类型变量到字节数组
    /// </summary>
    /// <param name="bytes">指定字节数组</param>
    /// <param name="value">具体的int值</param>
    /// <param name="index">每次存储后用于记录当前索引位置的变量</param>
    protected void WriteInt(byte[] bytes, int value, ref int index)
    {
        BitConverter.GetBytes(value).CopyTo(bytes, index);
        index += sizeof(int);
    }
    protected void WriteShort(byte[] bytes, short value, ref int index)
    {
        BitConverter.GetBytes(value).CopyTo(bytes, index);
        index += sizeof(short);
    }
    protected void Writefloat(byte[] bytes, float value, ref int index)
    {
        BitConverter.GetBytes(value).CopyTo(bytes, index);
        index += sizeof(float);
    }
    protected void Writelong(byte[] bytes, long value, ref int index)
    {
        BitConverter.GetBytes(value).CopyTo(bytes, index);
        index += sizeof(long);
    }
    protected void WriteByte(byte[] bytes, byte value, ref int index)
    {
        bytes[index] = value; index += sizeof(byte);
    }
    protected virtual void WriteBool(byte[] data, bool value, ref int index)
    {
        BitConverter.GetBytes(value).CopyTo(data, index);
        index += sizeof(bool);
    }
    protected virtual void WriteString(byte[] bytes, string value, ref int index)
    {
        //Debug.Log(bytes.Length);
 
        //先存字节数组长度
        byte[] bts = Encoding.UTF8.GetBytes(value);
        //Debug.Log(bts.Length);
        WriteInt(bytes, bts.Length, ref index);
        bts.CopyTo(bytes, index);
        index += bts.Length;
    }
    protected void WriteData(byte[] bytes, BaseData data, ref int index)
    {
        data.Writeing().CopyTo(bytes, index);
        index += data.GetBytesNum();
    }
    //------------------------------新增----------------------------------------
    protected void WriteDic<K, Y>(byte[] bytes, Dictionary<K, Y> Dic, ref int index)
    {
        // 存储字典长度
        WriteInt(bytes, Dic.Count, ref index);
        foreach (KeyValuePair<K, Y> dic in Dic)
        {
            DetectionType(dic.Key, bytes, ref index);
            DetectionType(dic.Value, bytes, ref index);
        }
    }
    protected void WriteList<T>(byte[] bytes, List<T> list, ref int index)
    {
        // 存储列表长度
        WriteInt(bytes, list.Count, ref index);
 
        // 根据类型写入数据
        foreach (var item in list)
        {
            DetectionType<T>(item, bytes, ref index);
        }
    }
    protected void WriteArray<T>(byte[] bytes, T[] array, ref int index)
    {
        // 写入数组长度
        WriteInt(bytes, array.Length, ref index);
        
        // 遍历数组并序列化每个元素
        foreach (var item in array)
        {
            if (item == null) return;
            // Debug.Log($"Type of T: {typeof(T)}, Type of item: {item.GetType()}");
            if (item is BaseData baseData)
            {
                // 如果元素是 BaseData 的子类,调用 WriteData
                WriteData(bytes, baseData, ref index);
            }
            else
            {
                // 否则调用 DetectionType 处理其他类型
                DetectionType(item, bytes, ref index);
            }
        }
    }
    private void DetectionType<T>(T value, byte[] bytes, ref int index)
    {
        if (value is int intValue)
        {
            WriteInt(bytes, intValue, ref index);
        }
        else if (value is float floatValue)
        {
            Writefloat(bytes, floatValue, ref index);
        }
        else if (value is short shortValue)
        {
            WriteShort(bytes, shortValue, ref index);
        }
        else if (value is long longValue)
        {
            Writelong(bytes, longValue, ref index);
        }
        else if (value is byte byteValue)
        {
            WriteByte(bytes, byteValue, ref index);
        }
        else if (value is bool boolValue)
        {
            WriteBool(bytes, boolValue, ref index);
        }
        else if (value is string strValue)
        {
            WriteString(bytes, strValue, ref index);
        }
        else if (value is BaseData baseData)
        {
            WriteData(bytes, baseData, ref index);
        }
        else
        {
           
            throw new ArgumentException("未定义的类型.");
        }
    }
    //------------------------------新增----------------------------------------
 
    protected int ReadInt(byte[] bytes, ref int index)
    {
        int value = BitConverter.ToInt32(bytes, index);
        index += sizeof(int);
        return value;
    }
    protected short ReadShort(byte[] bytes, ref int index)
    {
        short value = BitConverter.ToInt16(bytes, index);
        index += sizeof(short);
        return value;
    }
    protected long ReadLong(byte[] bytes, ref int index)
    {
        long value = BitConverter.ToInt16(bytes, index);
        index += sizeof(long);
        return value;
    }
    protected float ReadFloat(byte[] bytes, ref int index)
    {
        float value = BitConverter.ToSingle(bytes, index);
        index += sizeof(float);
        return value;
    }
    protected byte ReadByte(byte[] bytes, ref int index)
    {
        byte value = bytes[index];
        index += sizeof(byte);
        return value;
    }
    protected bool ReadBool(byte[] bytes, ref int index)
    {
        bool value = BitConverter.ToBoolean(bytes, index);
        index += sizeof(bool);
        return value;
    }
    protected string ReadString(byte[] bytes, ref int index)
    {
        int Length = ReadInt(bytes, ref index);
        string value = Encoding.UTF8.GetString(bytes, index, Length);
        index += Length;
        return value;
    }
    protected T ReadData<T>(byte[] bytes, ref int index) where T : BaseData, new()
    {
        T value = new T();
        index += value.Reading(bytes, index);
        return value;
    }
 
    //------------------------------新增----------------------------------------
    protected List<T> ReadList<T>(byte[] bytes, ref int index)
    {
        List<T> list = new List<T>();
 
        int count = BitConverter.ToInt32(bytes, index);
        index += sizeof(int);
 
        for (int i = 0; i < count; i++)
        {
            T item = default(T);
            item= ReadValue<T>(bytes, ref index);
            list.Add(item);
        }
 
        return list;
    }
    protected List<T> ReadList<T>(byte[] bytes, ref int index,bool isDataValue=false) where T : BaseData, new()
    {
        List<T> list = new List<T>();
 
        int count = ReadInt(bytes, ref index);
        for (int i = 0; i < count; i++)
        {
            list.Add(ReadData<T>(bytes, ref index));
        }
        return list;
    }
    protected Dictionary<K, Y> ReadDic<K, Y>(byte[] bytes, ref int index)
    {
        Dictionary<K, Y> dic = new Dictionary<K, Y>();
        int count = BitConverter.ToInt32(bytes, index);
        index += sizeof(int);
 
        for (int i = 0; i < count; i++)
        {
            K key = ReadValue<K>(bytes, ref index);
            Y value = ReadValue<Y>(bytes, ref index);
            dic.Add(key, value);
        }
        return dic;
    }
    protected T[] ReadArray<T>(byte[] bytes, ref int index)
    {
        // 读取数组长度
        int length = ReadInt(bytes, ref index);
 
        // 创建指定类型的数组
        T[] array = new T[length];
        // 遍历数组并反序列化每个元素
        for(int i = 0;i < length; i++) {
            array[i]= ReadValue<T>(bytes, ref index);
        }
        return array;
    }
    protected T[] ReadArray<T>(byte[] bytes, ref int index,bool isDataValue=false) where T : BaseData, new()
    {
        // 读取自定义类数组长度
        int length = ReadInt(bytes, ref index);
 
        // 创建指定类型的数组
        T[] array = new T[length];
        // 遍历数组并反序列化每个元素
        for (int i = 0; i < length; i++)
        {
            array[i] = ReadData<T>(bytes, ref index);
        }
        return array;
    }
    public Dictionary<K, Y> ReadDicData<K, Y>(byte[] bytes, ref int index) where Y : BaseData, new()
    {
        Dictionary<K, Y> dic = new Dictionary<K, Y>();
        int count = BitConverter.ToInt32(bytes, index);
        index += sizeof(int);
 
        for (int i = 0; i < count; i++)
        {
            K key = ReadValue<K>(bytes, ref index);
            Y value = ReadData<Y>(bytes, ref index);
            dic.Add(key, value);
        }
        return dic;
    }
    private T ReadValue<T>(byte[] bytes, ref int index)
    {
        if (typeof(T) == typeof(int))
        {
            int item = ReadInt(bytes, ref index);
            return (T)(object)item;
        }
        else if (typeof(T) == typeof(float))
        {
            float item = ReadFloat(bytes, ref index);
            return (T)(object)item;
        }
        else if (typeof(T) == typeof(short))
        {
            short item = ReadShort(bytes, ref index);
            return (T)(object)item;
        }
        else if (typeof(T) == typeof(long))
        {
            long item = ReadLong(bytes, ref index);
            return (T)(object)item;
        }
        else if (typeof(T) == typeof(byte))
        {
            byte item = ReadByte(bytes, ref index);
            return (T)(object)item;
        }
        else if (typeof(T) == typeof(bool))
        {
            bool item = ReadBool(bytes, ref index);
            return (T)(object)item;
        }
        else if (typeof(T) == typeof(string))
        {
            return (T)(object)ReadString(bytes, ref index);
        }
        else if (typeof(BaseData).IsAssignableFrom(typeof(T)))
        {
            throw new ArgumentException("调用者Value为BaseData子类,请调用ReadDicData方法来序列化字典!");
        }
        else
        {
            throw new ArgumentException("类型不存在.");
        }
    }
    //------------------------------新增----------------------------------------
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值