C#序列化和反序列化代码
来源:互联网 发布:淘宝详细地址怎么填 编辑:程序博客网 时间:2024/06/08 15:21
我们在日常开发中会经常用到序列化和反序列化,他们到底是什么意思呢?通俗的讲序列化就是把对象转化成数据文件或者字段(二进制或者XML),反序列化就是数据文件或者字段转化为数据对象。 下面我以提问题的方式,帮大家解释一下序列化和反序列化。(C#代码为例)
一 、为什么使用序列化和反序列化?
1.保存对象。通常我们在C#代码中构建了一个对象需要把该对象保存到数据库、文件、Application、Session、Coockie、ViewState等其他存储环境中,以备下次直接使用。
2.共享数据. 对象仅在创建对象的应用程序域中有效,其他应用程序域想调用该对象数据就会使用该技术。
3.在网络上传送对象的字节序列。其中Web Service就是一个典型的例证。
4.在一些分布式系统中也经常会用到该技术。
二、序列化和反序列化有哪些类型?
在C#中序列化反序列化类型大致有如下三种:
第一、二进制数据(BinaryFormatter->IFormatter)
第二、XML数据(XmlSerializer)
第三、Soap数据(SoapFormatter->IFormatter)
三、序列化和反序列化分别如何实现?
共用类(UserInFo)
/// <summary>
/// UserInfo for public test smaple
/// </summary>
[Serializable]
public class UserInfo
{
#region Database fields
private System.Int32 _UserID;
private System.String _UserName;
private System.Int16 _UserType;
private System.String _Email;
private System.String _Pwd;
private System.String _Firstname;
private System.String _Lastname;
#endregion
#region GETs and SETs
public System.Int32 UserID
{
get {return _UserID; }
set { _UserID= value; }
}
public System.String UserName
{
get {return _UserName; }
set { _UserName= value; }
}
public System.Int16 UserType
{
get {return _UserType; }
set { _UserType= value; }
}
public System.String Email
{
get {return _Email; }
set { _Email= value; }
}
public System.String Pwd
{
get {return _Pwd; }
set { _Pwd= value; }
}
public System.String Firstname
{
get {return _Firstname; }
set { _Firstname= value; }
}
public System.String Lastname
{
get {return _Lastname; }
set { _Lastname= value; }
}
#endregion
public UserInfo()
{
}
}
/// <summary>
/// UserInfo for public test smaple
/// </summary>
[Serializable]
public class UserInfo
{
#region Database fields
private System.Int32 _UserID;
private System.String _UserName;
private System.Int16 _UserType;
private System.String _Email;
private System.String _Pwd;
private System.String _Firstname;
private System.String _Lastname;
#endregion
#region GETs and SETs
public System.Int32 UserID
{
get {return _UserID; }
set { _UserID= value; }
}
public System.String UserName
{
get {return _UserName; }
set { _UserName= value; }
}
public System.Int16 UserType
{
get {return _UserType; }
set { _UserType= value; }
}
public System.String Email
{
get {return _Email; }
set { _Email= value; }
}
public System.String Pwd
{
get {return _Pwd; }
set { _Pwd= value; }
}
public System.String Firstname
{
get {return _Firstname; }
set { _Firstname= value; }
}
public System.String Lastname
{
get {return _Lastname; }
set { _Lastname= value; }
}
#endregion
public UserInfo()
{
}
}
第一、二进制数据
按 Ctrl+C 复制代码
按 Ctrl+C 复制代码
反序列化二进制代码
public static UserInfo Deserialize(byte[] byteArray)
{
IFormatter formatter =new BinaryFormatter();
MemoryStream ms =new MemoryStream();
ms.Write(byteArray, 0, byteArray.Length);
ms.Position =0;
UserInfo usr = formatter.Deserialize(ms)as UserInfo;
return usr;
}
public static UserInfo Deserialize(byte[] byteArray)
{
IFormatter formatter =new BinaryFormatter();
MemoryStream ms =new MemoryStream();
ms.Write(byteArray, 0, byteArray.Length);
ms.Position =0;
UserInfo usr = formatter.Deserialize(ms)as UserInfo;
return usr;
}
第二、Xml数据
序列化XML代码
publicstatic XmlDocument Serialize(UserInfo usr)
{
XmlSerializer lizer =new XmlSerializer(usr.GetType());
MemoryStream ms =new MemoryStream();
lizer.Serialize(ms, usr);
XmlDocument doc=new XmlDocument();
doc.Load(ms);
return doc;
}
publicstatic XmlDocument Serialize(UserInfo usr)
{
XmlSerializer lizer =new XmlSerializer(usr.GetType());
MemoryStream ms =new MemoryStream();
lizer.Serialize(ms, usr);
XmlDocument doc=new XmlDocument();
doc.Load(ms);
return doc;
}
反序列化XML代码
publicstatic UserInfo DeserializeXml(XmlDocument doc)
{
XmlSerializer lizer =new XmlSerializer(typeof(UserInfo));
StringReader reader =new StringReader(doc.OuterXml);
UserInfo usr = lizer.Deserialize(reader)as UserInfo;
return usr;
}
publicstatic UserInfo DeserializeXml(XmlDocument doc)
{
XmlSerializer lizer =new XmlSerializer(typeof(UserInfo));
StringReader reader =new StringReader(doc.OuterXml);
UserInfo usr = lizer.Deserialize(reader)as UserInfo;
return usr;
}
第三、Soap数据
序列化代码
staticvoid Serialize()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable addresses =new Hashtable();
addresses.Add("Jeff","123 Main Street, Redmond, WA 98052");
addresses.Add("Fred","987 Pine Road, Phila., PA 19116");
addresses.Add("Mary","PO Box 112233, Palo Alto, CA 94301");
// To serialize the hashtable (and its key/value pairs),
// you must first open a stream for writing.
// Use a file stream here.
FileStream fs =new FileStream("DataFile.soap", FileMode.Create);
// Construct a SoapFormatter and use it
// to serialize the data to the stream.
SoapFormatter formatter =new SoapFormatter();
try
{
formatter.Serialize(fs, addresses);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason:" + e.Message);
throw;
}
finally
{
fs.Close();
}
}
staticvoid Serialize()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable addresses =new Hashtable();
addresses.Add("Jeff","123 Main Street, Redmond, WA 98052");
addresses.Add("Fred","987 Pine Road, Phila., PA 19116");
addresses.Add("Mary","PO Box 112233, Palo Alto, CA 94301");
// To serialize the hashtable (and its key/value pairs),
// you must first open a stream for writing.
// Use a file stream here.
FileStream fs =new FileStream("DataFile.soap", FileMode.Create);
// Construct a SoapFormatter and use it
// to serialize the data to the stream.
SoapFormatter formatter =new SoapFormatter();
try
{
formatter.Serialize(fs, addresses);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason:" + e.Message);
throw;
}
finally
{
fs.Close();
}
}
反序列化代码
static void Deserialize()
{
// Declare the hashtable reference.
Hashtable addresses =null;
// Open the file containing the data that you want to deserialize.
FileStream fs =new FileStream("DataFile.soap", FileMode.Open);
try
{
SoapFormatter formatter =new SoapFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
addresses = (Hashtable) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason:" + e.Message);
throw;
}
finally
{
fs.Close();
}
// To prove that the table deserialized correctly,
// display the key/value pairs to the console.
foreach (DictionaryEntry dein addresses)
{
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
static void Deserialize()
{
// Declare the hashtable reference.
Hashtable addresses =null;
// Open the file containing the data that you want to deserialize.
FileStream fs =new FileStream("DataFile.soap", FileMode.Open);
try
{
SoapFormatter formatter =new SoapFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
addresses = (Hashtable) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason:" + e.Message);
throw;
}
finally
{
fs.Close();
}
// To prove that the table deserialized correctly,
// display the key/value pairs to the console.
foreach (DictionaryEntry dein addresses)
{
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
- C#序列化和反序列化代码
- c# 序列化和反序列化
- C#序列化和反序列化
- C#序列化和反序列化
- C#序列化和反序列化
- c#序列化和反序列化
- C#序列化和反序列化
- C#序列化和反序列化
- C# - 序列化和反序列化
- C#序列化和反序列化
- C#序列化和反序列化
- C#序列化和反序列化
- C#序列化和反序列化
- C#序列化和反序列化
- C# 序列化和反序列化
- C# 序列化和反序列化
- C# 序列化和反序列化
- C#序列化和反序列化
- 查询oracle数据库的数据库名、实例名、ORACLE_SID
- 动态链接逐一注册
- PHP 开发API接口 注册,登录,查询用户资料
- js生成无刷新省市级联菜单
- 拼凑的回忆伤感日志_思念,才是真正的永恒,真正的痛!
- C#序列化和反序列化代码
- 一位前辈工程师职业发展的忠告 深有同感!
- APT进阶持续性威胁,主要目标攻击侵入点:eMail
- linux内核链表
- intrinsic image decomposition
- Present ViewController Modally
- 一道好题
- 谋杀上班时间的50个绝好网站 上班不无聊了
- win7上的高级外观设置(设置窗口颜色,对话框颜色等)