C#实现序列化和反序列化

时间:2022-10-01 15:51:32

从我们面试准备上面,我知道了一个知识点,就是我们vs提供的序列化方法有两个,一个叫二进制序列化,一个叫做xml序列化,下面我们说一下二进制序列化的C#实现:

反序列化:

public static T Desrialize<T>(T obj, string str)
{
try
{
obj = default(T);
IFormatter formatter = new BinaryFormatter();
byte[] buffer = Convert.FromBase64String(str);
MemoryStream stream = new MemoryStream(buffer);
obj = (T)formatter.Deserialize(stream);
stream.Flush();
stream.Close();
}
catch (Exception ex)
{
//throw new Exception("反序列化失败,原因:" + ex.Message);
return obj;
}
return obj;
}

序列化:       

 public static string Serialize<T>(T obj)
{
try
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, obj);
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Flush();
stream.Close();
return Convert.ToBase64String(buffer);
}
catch (Exception ex)
{
throw new Exception("序列化失败,原因:" + ex.Message);
}
}
反序列化:
        public static T Desrialize<T>(T obj, string str)
        {
            try
            {
                obj = default(T);
                IFormatter formatter = new BinaryFormatter();
                byte[] buffer = Convert.FromBase64String(str);
                MemoryStream stream = new MemoryStream(buffer);
                obj = (T)formatter.Deserialize(stream);
                stream.Flush();
                stream.Close();
            }
            catch (Exception ex)
            {
                //throw new Exception("反序列化失败,原因:" + ex.Message);
                return obj;
            }
            return obj;
        }



序列化:
        public static string Serialize<T>(T obj)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                formatter.Serialize(stream, obj);
                stream.Position = 0;
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Flush();
                stream.Close();
                return Convert.ToBase64String(buffer);
            }
            catch (Exception ex)
            {
                throw new Exception("序列化失败,原因:" + ex.Message);
            }
        }