刚刚碰巧群里有人问这个问题,而之前的博客中并没有提及,打算弄一篇博客简单提及一下这个知识点。
MSDN文档中提及了序列化、反序列化的概念,这里引用一下。
序列化:将对象状态转换为可保持或传输的形式的过程。
反序列化:是序列化的逆过程,就是将流转换为对象的过程。
这两个过程一起保证数据易于传输和存储。
详细的请参考:http://msdn.microsoft.com/zh-cn/library/7ay27kt9(v=vs.100).aspx。
下面直接给出完整的代码,该代码演示了如何序列化一个对象以及反序列化(还原对象)的过程。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Object student = new Student() { StudentID = "007", StudentName = "guwei4037" };
string result = ObjectToString<Object>(student);
Console.WriteLine(result + "\r\n");
Student newResult = StringToObject<Student>(result);
Console.WriteLine("ID:{0}, Name:{1}", newResult.StudentID, newResult.StudentName);
}
/// <summary>
/// 对象转字符串(序列化后转Base64编码字符串)
/// </summary>
/// <param name="obj">对象</param>
/// <returns>字符串</returns>
public static string ObjectToString<T>(T obj)
{
using (MemoryStream stream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
return Convert.ToBase64String(buffer);
}
}
/// <summary>
/// 字符串转对象(Base64编码字符串反序列化为对象)
/// </summary>
/// <param name="str">字符串</param>
/// <returns>对象</returns>
public static T StringToObject<T>(string str)
{
using (MemoryStream stream = new MemoryStream())
{
byte[] bytes = Convert.FromBase64String(str);
stream.Write(bytes, 0, bytes.Length);
stream.Position = 0;
IFormatter formatter = new BinaryFormatter();
return (T)formatter.Deserialize(stream);
}
}
}
/// <summary>
/// 可序列化的类,用Serializable标示此类可序列化
/// </summary>
[Serializable]
public class Student
{
public string StudentID { get; set; }
public string StudentName { get; set; }
}
}
运行结果截图:
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。