using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;
public sealed class Serializer
{
    private Serializer() { }

    public static string SerializeObject(object obj)
    {
        IFormatter formatter = new BinaryFormatter();
        string result = string.Empty;
        using (MemoryStream stream = new MemoryStream())
        {
            formatter.Serialize(stream, obj);

            byte[] byt = new byte[stream.Length];
            byt = stream.ToArray();
            //result = Encoding.UTF8.GetString(byt, 0, byt.Length);

            result = Convert.ToBase64String(byt);
            stream.Flush();
        }
        return result;
    }

    public static object DeserializeObject(string str)
    {
        IFormatter formatter = new BinaryFormatter();
        //byte[] byt = Encoding.UTF8.GetBytes(str);

        byte[] byt = Convert.FromBase64String(str);
        object obj = null;
        using (Stream stream = new MemoryStream(byt, 0, byt.Length))
        {
            obj = formatter.Deserialize(stream);
        }
        return obj;
    }
}

再次单元测试通过了,说明修改有效,回头debug到“result = Convert.ToBase64String(byt); ”,result的值开头没有"\0"了,都是字母,这才证明了序列化成功的原因。之后对基于64位的字符串转换应该多加关注,往往能起到令人惊喜的效果,本案总算是结案了。

相关文章:

  • 2021-09-04
  • 2021-09-30
  • 2021-06-18
  • 2022-12-23
  • 2021-06-22
  • 2021-10-04
  • 2020-05-13
  • 2021-09-09
猜你喜欢
  • 2021-05-31
  • 2022-02-14
  • 2022-12-23
  • 2021-08-07
  • 2021-12-19
  • 2022-12-23
相关资源
相似解决方案