序列化简言之是这样一种能力:能够把复杂的对象(Object)变成某种格式的字符串(常见的格式有xml,string,二进制文件等),这样可以方便的在各种系统中传输或交换(比喻socket编程中的数据包只能用byte[]传输),接收方得到该字符串后,通过反序列化可以还原为复杂对象,进而调用对象的方法或属性 -- 跟反射有点沾边:)
这里先给出一个WinForm的序列化例子,功能为通过打开文件对话框选择一个文件后,构造一个复杂对象,然后序列化为二进制格式,得到该格式后,再反序列化(还原)为复杂对象
1
using
System;
2 System.IO;
3 System.Runtime.Serialization;
4 System.Runtime.Serialization.Formatters.Binary;
5 System.Text;
6 System.Windows.Forms;
7
8 namespace SerializeStudy
9 {
10 public partial class Form1 : Form
11 {
12 Form1()
13 {
14 InitializeComponent();
15 }
16 17 private void btnSerialize_Click( object sender, EventArgs e)
18 19 OpenFileDialog opendlg = new OpenFileDialog();
20 if (opendlg.ShowDialog() == DialogResult.OK)
21 {
22 23 #region 得到一个包含"文件内容"的Msg对象 24 Msg msg Msg();
25 msg.ReceiverName " jimmy " ;
26 msg.SenderName yjmyzy 27 msg.Type MessageType.file;
28 FileStream fs opendlg.OpenFile() as FileStream;
29 msg.Body byte [fs.Length];
30 fs.Read(msg.Body, 0 , msg.Body.Length);
31 fs.Close();
32 #endregion 33 34 将Msg对象序列到内存流中 35 MemoryStream ms MemoryStream();
36 BinaryFormatter binaryFormatter BinaryFormatter();
37 binaryFormatter.Serialize(ms, msg);
38 39 40 再将内存流转化为byte[] 41 [] arrMsg ms.ToArray();
42 ms.Close();
43 44 45 MessageBox.Show( 序列化成功! );
46 47 StringBuilder sb StringBuilder();
48 49 for ( int i ; i < arrMsg.Length; i ++ )
50 {
51 sb.Append(arrMsg[i].ToString() + ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, 52 }
53 54 textBox1.Text sb.ToString().Trim( ' ' 55 }
56 57 58 btnDeSerialize_Click( 59 60 (textBox1.Text.Trim().Length ) { return ; }
61 62 先将textBox1中的内容变成byte[] 63 string textBox1.Text.Trim().Split( 64 [] arrBin [arrMsg.Length];
65 66 67 68 arrBin[i] .Parse(arrMsg[i]);
69 70 71 72 try 73 74 IFormatter formatter 75 MemoryStream(arrBin);
76 formatter.Deserialize(ms) Msg;
77 78 (msg != null 79 80 MessageBox.Show( 反序列化成功! msg.ReceiverName msg.SenderName msg.Type);
81 82 83 84 catch (Exception ex)
85 86 MessageBox.Show(ex.Message.ToString());
87 88 89 }
90 91 92 93 /// <summary> 94 消息格式
95 </summary>
96 [Serializable]
97 enum MessageType
98 99 txt,
100 img,128)">101 file,128)">102 unkNown
103 104 105 106 消息对象
107 108 109 Msg
110 111 MessageType _type MessageType.unkNown;
112 MessageType Type
113 114 set { _type value; }
115 get { _type; }
116 117 118 SenderName { ; 119 ReceiverName { 120 [] Body { 121 122 123 }
124
2 System.IO;
3 System.Runtime.Serialization;
4 System.Runtime.Serialization.Formatters.Binary;
5 System.Text;
6 System.Windows.Forms;
7
8 namespace SerializeStudy
9 {
10 public partial class Form1 : Form
11 {
12 Form1()
13 {
14 InitializeComponent();
15 }
16 17 private void btnSerialize_Click( object sender, EventArgs e)
18 19 OpenFileDialog opendlg = new OpenFileDialog();
20 if (opendlg.ShowDialog() == DialogResult.OK)
21 {
22 23 #region 得到一个包含"文件内容"的Msg对象 24 Msg msg Msg();
25 msg.ReceiverName " jimmy " ;
26 msg.SenderName yjmyzy 27 msg.Type MessageType.file;
28 FileStream fs opendlg.OpenFile() as FileStream;
29 msg.Body byte [fs.Length];
30 fs.Read(msg.Body, 0 , msg.Body.Length);
31 fs.Close();
32 #endregion 33 34 将Msg对象序列到内存流中 35 MemoryStream ms MemoryStream();
36 BinaryFormatter binaryFormatter BinaryFormatter();
37 binaryFormatter.Serialize(ms, msg);
38 39 40 再将内存流转化为byte[] 41 [] arrMsg ms.ToArray();
42 ms.Close();
43 44 45 MessageBox.Show( 序列化成功! );
46 47 StringBuilder sb StringBuilder();
48 49 for ( int i ; i < arrMsg.Length; i ++ )
50 {
51 sb.Append(arrMsg[i].ToString() + ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, 52 }
53 54 textBox1.Text sb.ToString().Trim( ' ' 55 }
56 57 58 btnDeSerialize_Click( 59 60 (textBox1.Text.Trim().Length ) { return ; }
61 62 先将textBox1中的内容变成byte[] 63 string textBox1.Text.Trim().Split( 64 [] arrBin [arrMsg.Length];
65 66 67 68 arrBin[i] .Parse(arrMsg[i]);
69 70 71 72 try 73 74 IFormatter formatter 75 MemoryStream(arrBin);
76 formatter.Deserialize(ms) Msg;
77 78 (msg != null 79 80 MessageBox.Show( 反序列化成功! msg.ReceiverName msg.SenderName msg.Type);
81 82 83 84 catch (Exception ex)
85 86 MessageBox.Show(ex.Message.ToString());
87 88 89 }
90 91 92 93 /// <summary> 94 消息格式
95 </summary>
96 [Serializable]
97 enum MessageType
98 99 txt,
100 img,128)">101 file,128)">102 unkNown
103 104 105 106 消息对象
107 108 109 Msg
110 111 MessageType _type MessageType.unkNown;
112 MessageType Type
113 114 set { _type value; }
115 get { _type; }
116 117 118 SenderName { ; 119 ReceiverName { 120 [] Body { 121 122 123 }
124
不过在Silverlight中,传统的序列化方式有很多被精减掉了(比如BinaryFormatter之类),唯一得以保存的只剩下System.Xml.Serialization,所以SL中只能通过xml来序列化对象(虽然xml序列化后的字节数相对Binary有点大,不过我们也别无选择),另外有一点很让人不习惯的是,需要序列化的自定义类中,居然不需要加[Serializable],[DataMember]这类标记!(这一点让我郁闷了好久,还为此在网上疯狂的百度,google为啥sl中不识别Serializable)
1.先定义一个需要序列化的类
namespace
SerializeDemo
{
/// <summary>
聊天室消息对象
</summary>
public class ChatMessage
{
string SenderName { set ; get ; }
ReceiverName { MessageType Type { byte [] Body { enum MessageType {
txt,img,file,unkNown
}
}
}
{
/// <summary>
聊天室消息对象
</summary>
public class ChatMessage
{
string SenderName { set ; get ; }
ReceiverName { MessageType Type { byte [] Body { enum MessageType {
txt,img,file,unkNown
}
}
}
2.序列化/反序列化代码示例:
Xaml部分:
Xaml
<
UserControl
x:Class
="SerializeDemo.MainPage"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable ="d" d:DesignWidth ="640" d:DesignHeight ="480" >
Grid x:Name ="LayoutRoot"
Grid.RowDeFinitions
RowDeFinition Height ="30" /> ="*" </ StackPanel HorizontalAlignment ="Center" Orientation ="Horizontal" Button ="btnSerialize" Content ="序列化" Width ="80" Height ="24" Click ="btnSerialize_Click" ="btnDeSerialize" ="反序列化" Margin ="10,0" ="btnDeSerialize_Click" StackPanel TextBox Grid.Row ="1" Text ="TextBox" textwrapping ="Wrap" d:LayoutOverrides ="Height" x:Name ="txtResult"
Grid
UserControl >
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable ="d" d:DesignWidth ="640" d:DesignHeight ="480" >
Grid x:Name ="LayoutRoot"
Grid.RowDeFinitions
RowDeFinition Height ="30" /> ="*" </ StackPanel HorizontalAlignment ="Center" Orientation ="Horizontal" Button ="btnSerialize" Content ="序列化" Width ="80" Height ="24" Click ="btnSerialize_Click" ="btnDeSerialize" ="反序列化" Margin ="10,0" ="btnDeSerialize_Click" StackPanel TextBox Grid.Row ="1" Text ="TextBox" textwrapping ="Wrap" d:LayoutOverrides ="Height" x:Name ="txtResult"
Grid
UserControl >
Xaml.cs部分:
using
System;
System.IO;
System.Text;
System.Windows;
System.Windows.Controls;
System.Xml.Serialization;
SerializeDemo
{
partial MainPage : UserControl
{
MainPage()
{
InitializeComponent();
}
private void btnSerialize_Click( object ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, RoutedEventArgs e)
{
#region 得到一个复杂对象
ChatMessage msg = new ChatMessage();
msg.ReceiverName " jimmy " ;
msg.SenderName yjmyzy ;
msg.Type ChatMessage.MessageType.file;
msg.Body [] { 0 ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, 1 };
#endregion
MemoryStream ms MemoryStream();
XmlSerializer xml XmlSerializer( typeof (ChatMessage));
try
{
xml.Serialize(ms, msg); // 将对象序列化为流 [] arr ms.ToArray();
StringBuilder sb StringBuilder();
for ( int i ; i < arr.Length; i ++ )
{
sb.Append(arr[i].ToString() + ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, );
}
txtResult.Text sb.ToString().Trim( ' ' );
}
catch (Exception ex)
{
txtResult.Text ex.Message.ToString();
}
}
btnDeSerialize_Click( if (txtResult.Text.Trim().Length == ) { return ; }
先将txtResult中的内容变成byte[]
[] arrMsg txtResult.Text.Trim().Split( );
[] arrBin [arrMsg.Length];
arrMsg.Length; i )
{
arrBin[i] .Parse(arrMsg[i]);
}
MemoryStream ms MemoryStream(arrBin);
XmlSerializer xml
{
ChatMessage msg xml.Deserialize(ms) as ChatMessage; 反序列化为ChatMessage对象 (msg != null )
{
txtResult.Text 反序列化成功! msg.ReceiverName msg.SenderName msg.Type.ToString();
}
}
ex.Message.ToString();
}
}
}
}
System.IO;
System.Text;
System.Windows;
System.Windows.Controls;
System.Xml.Serialization;
SerializeDemo
{
partial MainPage : UserControl
{
MainPage()
{
InitializeComponent();
}
private void btnSerialize_Click( object ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, RoutedEventArgs e)
{
#region 得到一个复杂对象
ChatMessage msg = new ChatMessage();
msg.ReceiverName " jimmy " ;
msg.SenderName yjmyzy ;
msg.Type ChatMessage.MessageType.file;
msg.Body [] { 0 ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, 1 };
#endregion
MemoryStream ms MemoryStream();
XmlSerializer xml XmlSerializer( typeof (ChatMessage));
try
{
xml.Serialize(ms, msg); // 将对象序列化为流 [] arr ms.ToArray();
StringBuilder sb StringBuilder();
for ( int i ; i < arr.Length; i ++ )
{
sb.Append(arr[i].ToString() + ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, );
}
txtResult.Text sb.ToString().Trim( ' ' );
}
catch (Exception ex)
{
txtResult.Text ex.Message.ToString();
}
}
btnDeSerialize_Click( if (txtResult.Text.Trim().Length == ) { return ; }
先将txtResult中的内容变成byte[]
[] arrMsg txtResult.Text.Trim().Split( );
[] arrBin [arrMsg.Length];
arrMsg.Length; i )
{
arrBin[i] .Parse(arrMsg[i]);
}
MemoryStream ms MemoryStream(arrBin);
XmlSerializer xml
{
ChatMessage msg xml.Deserialize(ms) as ChatMessage; 反序列化为ChatMessage对象 (msg != null )
{
txtResult.Text 反序列化成功! msg.ReceiverName msg.SenderName msg.Type.ToString();
}
}
ex.Message.ToString();
}
}
}
}
作者:
菩提树下的杨过
出处: http://yjmyzz.cnblogs.com 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处: http://yjmyzz.cnblogs.com 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。