大佬教程收集整理的这篇文章主要介绍了Silverlight中的序列化,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
序 列化简言之是这样一种能力:能够把复杂的对象(Object)变成某种格式的字符串(常见的格式有xml,String,二进制文件等),这样可以方便的 在各种系统中传输或交换(比喻socket编程中的数据包只能用byte[]传输),接收方得到该字符串后,通过反序列化可以还原为复杂对象,进而调用对 象的方法或属性 -- 跟反射有点沾边:)
这里先给出一个WinForm的序列化例子,功能为通过打开文件对话框选择一个文件后,构造一个复杂对象,然后序列化为二进制格式,得到该格式后,再反序列化(还原)为复杂对象
Winform中的序列化
1 using System;
2 using System.IO;
3 using System.Runtime.serialization;
4 using System.Runtime.serialization.Formatters.binary;
5 using System.Text;
6 using System.Windows.Forms;
7
8 namespace serializestudy
9 {
10 public partial class Form1 : Form
11 {
12 public 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 得到一个包含"文件@L_674_18@"的Msg对象
24 Msg msg = new Msg();
25 msg.ReceiverName = "jimmy";
26 msg.SenderName = "yjmyzy";
27 msg.Type = messageType.file;
28 FileStream fs = opendlg.openFile() as FileStream;
29 msg.body = new byte[fs.Length];
30 fs.Read(msg.body,msg.body.Length);
31 fs.Close();
32 #endregion
33
34 #region 将Msg对象序列到内存流中
35 MemoryStream ms = new MemoryStream();
36 BinaryFormatter binaryFormatter = new BinaryFormatter();
37 binaryFormatter.serialize(ms,msg);
38 #endregion
39
40 #region 再将内存流转化为byte[]
41 byte[] arrMsg = ms.ToArray();
42 ms.Close();
43 #endregion
44
45 messageBox.Show("序列化成功!");
46
47 StringBuilder sb = new StringBuilder();
48
49 for (int i = 0; i < arrMsg.Length; i++)
50 {
51 sb.Append(arrMsg[i].ToString() + ",");
52 }
53
54 TEXTBox1.Text = sb.ToString().Trim(',');
55 }
56 }
57
58 private void btnDeserialize_Click(object sender,EventArgs E)
59 {
60 if (textBox1.Text.Trim().Length == 0) { return; }
61
62 #region 先将textBox1中的@L_674_18@变成byte[]
63 String[] arrMsg = textBox1.Text.Trim().Split(',');
64 byte[] arrBin = new byte[arrMsg.Length];
65
66 for (int i = 0; i < arrMsg.Length; i++)
67 {
68 arrBin[i] = byte.Parse(arrMsg[i]);
69 }
70 #endregion
71
72 try
73 {
74 IFormatter formatter = new BinaryFormatter();
75 MemoryStream ms = new MemoryStream(arrBin);
76 Msg msg = formatter.Deserialize(ms) as Msg;
77
78 if (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 public enum messageType
98 {
99 txt,
100 img,
101 file,
102 unkNown
103 }
104
105 /// <sumMary>
106 /// 消息对象
107 /// </sumMary>
108 [serializable]
109 public class Msg
110 {
111 private messageType _type = messageType.unkNown;
112 public messageType Type
113 {
114 set { _type = value; }
115 get { return _type; }
116 }
117
118 public String SenderName { set; get; }
119 public String ReceiverName { set; get; }
120 public byte[] Body { set; get; }
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
{
public String SenderName { set; get; }
public String ReceiverName { set; get; }
public messageType Type { set; get; }
public byte[] Body { set; get; }
public 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"/>
<RowDeFinition Height="*"/>
</Grid.RowDeFinitions>
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
<Button x:Name="btnserialize" Content="序列化" Width="80" Height="24" Click="btnserialize_Click"/>
<Button x:Name="btnDeserialize" Content="反序列化" Width="80" Margin="10,0" Height="24" Click="btnDeserialize_Click"/>
</StackPanel>
<TextBox Grid.Row="1" Text="TextBox" textwrapping="Wrap" d:LayoutOverrides="Height" x:Name="txtResult"/>
</Grid>
</UserControl>
Xaml.cs部分:
Xaml.cs
using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Xml.serialization;
namespace serializeDemo
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void btnserialize_Click(object sender,RoutedEventArgs E)
{
#region 得到一个复杂对象
Chatmessage msg = new Chatmessage();
msg.ReceiverName = "jimmy";
msg.SenderName = "yjmyzy";
msg.type = chatmessage.messageType.file;
msg.body = new byte[] { 0,1,1 };
#endregion
MemoryStream ms = new MemoryStream();
Xmlserializer xml = new Xmlserializer(typeof(ChatmessagE));
try
{
xml.serialize(ms,msg);//将对象序列化为流
byte[] arr = ms.ToArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.Length; i++)
{
sb.Append(arr[i].ToString() + ",");
}
txtResult.Text = sb.ToString().Trim(',');
}
catch (Exception eX)
{
txtResult.Text = ex.message.ToString();
}
}
private void btnDeserialize_Click(object sender,RoutedEventArgs E)
{
if (txtResult.Text.Trim().Length == 0) { return; }
#region 先将txtResult中的@L_674_18@变成byte[]
String[] arrMsg = txtResult.Text.Trim().Split(',');
byte[] arrBin = new byte[arrMsg.Length];
for (int i = 0; i < arrMsg.Length; i++) { arrBin[i] = byte.Parse(arrMsg[i]); } #endregion MemoryStream ms = new MemoryStream(arrBin); Xmlserializer xml = new Xmlserializer(typeof(ChatmessagE)); try { Chatmessage msg = xml.Deserialize(ms) as Chatmessage;//反序列化为Chatmessage对象 if (msg != null) { txtResult.Text = "反序列化成功!" + msg.ReceiverName + "," + msg.Type.ToString(); } } catch (Exception eX) { txtResult.Text = ex.message.ToString(); } } } }
以上是大佬教程为你收集整理的Silverlight中的序列化全部内容,希望文章能够帮你解决Silverlight中的序列化所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。