C# 序列化 反序列化

/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
private static byte[]? Serialize<T>(T? obj)
{
    if (obj == null)
        return default;
    using var memoryStream = new MemoryStream();
    DataContractSerializer ser = new(typeof(T));
    ser.WriteObject(memoryStream, obj);
    var data = memoryStream.ToArray();
    return data;
}

/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
private static T? Deserialize<T>(byte[]? data)
{
    if (data == null)
        return default;
    using var memoryStream = new MemoryStream(data);
    XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas());
    DataContractSerializer ser = new(typeof(T));
    var result = (T?)ser.ReadObject(reader, true);
    return result;
}

 

posted @ 2023-02-16 16:00  Mr_Xul  阅读(19)  评论(0编辑  收藏  举报