求对象 序列华 反序列化示例 求对象 序列华 反序列化示例 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 对象的序列化 http://www.cnblogs.com/ring1981/archive/2006/07/18/453512.html.net中对象的序列化是指将对象的状态存储起来,先将对象的字段和属性以及类名转换为字节流,然后再把字节流写入数据流。通过对对象反序列化,得到原对象完全相同的副本。对象的序列化主要的目的是将对象持久化,经过持久化的对象可以从一个地方传输到另一个地方。在.net中, IFormatter接口提供了对象序列化的功能。他有两个公有的方法:反序列化对象方法Deserialize : Deserializes the data on the provided stream and reconstitutes the graph of objects。序列化对象方法Serialize:Serializes an object, or graph of objects with the given root to the provided stream。我们可以将对象序列化成两种格式:BinaryFormatter :将对象序列化为二进制格式SoapFormatter:将对象序列化为Soap格式代码://要进行序列化的类 1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace SerializeDemos 6{ 7 [Serializable] 8 public class Car 9 {10 private string _Price;11 private string _Owner;12 public string Price13 {14 get { return this._Price; }15 set { this._Price = value; }16 }17 public string Owner18 {19 get { return this._Owner; }20 set { this._Owner = value; }21 }22 public Car(string o, string p)23 {24 this.Price = p;25 this.Owner = o;26 }27 }28}29//序列化以及反序列化对象 1using System; 2using System.Collections.Generic; 3using System.ComponentModel; 4using System.Data; 5using System.Drawing; 6using System.Text; 7using System.Windows.Forms; 8using System.IO; 9using System.Runtime.Serialization.Formatters.Binary;10using System.Runtime.Serialization.Formatters.Soap;11using System.Xml.Serialization;121314namespace SerializeDemos15{1617 public partial class Form1 : Form18 {19 public Form1()20 {21 InitializeComponent();22 }23 private void Form1_Load(object sender, EventArgs e)24 {2526 }2728 private void button1_Click(object sender, EventArgs e)29 {30 Car car = new Car(this.txtOwner.Text, this.txtPrice.Text);31 FileStream fileStream = new FileStream("SerializedCar.bin", FileMode.Create);32 // 用二进制格式序列化33 BinaryFormatter binaryFormatter = new BinaryFormatter();34 binaryFormatter.Serialize(fileStream, car);35 fileStream.Close();36 MessageBox.Show("Successful");37 }3839 private void button2_Click(object sender, EventArgs e)40 {41 Car car = new Car(this.txtOwner.Text, this.txtPrice.Text);42 FileStream fileStream = new FileStream("SerializedCar.Soap", FileMode.Create);43 // 序列化为Soap44 SoapFormatter formatter = new SoapFormatter();45 formatter.Serialize(fileStream, car);46 fileStream.Close();47 MessageBox.Show("Successful");48 }4950 private void button3_Click(object sender, EventArgs e)51 {52 Car car = new Car(this.txtOwner.Text, this.txtPrice.Text);53 FileStream fileStream = new FileStream("SerializedCar.xml", FileMode.Create);54 // 序列化为xml55 SoapFormatter formatter = new SoapFormatter();56 formatter.Serialize(fileStream, car);57 fileStream.Close();58 MessageBox.Show("Successful");59 }6061 private void button4_Click(object sender, EventArgs e)62 { 63 System.Runtime.Serialization.IFormatter formatter = new BinaryFormatter();64 //二进制格式反序列化65 Stream stream = new FileStream("SerializedCar.bin", FileMode.Open, FileAccess.Read, FileShare.Read);66 Car mycar = (Car)formatter.Deserialize(stream);67 stream.Close();68 MessageBox.Show(string.Format("Price of Car: {0},\n Owner:{1}", mycar.Price, mycar.Owner));69 }7071 private void button5_Click(object sender, EventArgs e)72 {73 System.Runtime.Serialization.IFormatter formatter = new SoapFormatter();74 //Soap格式反序列化75 Stream stream = new FileStream("SerializedCar.Soap", FileMode.Open, FileAccess.Read, FileShare.Read);76 Car mycar = (Car)formatter.Deserialize(stream);77 stream.Close();78 MessageBox.Show(string.Format("Price of Car: {0},\n Owner:{1}", mycar.Price, mycar.Owner));79 }8081 private void button6_Click(object sender, EventArgs e)82 {83 System.Runtime.Serialization.IFormatter formatter = new SoapFormatter();84 //Xml格式反序列化85 Stream stream = new FileStream("SerializedCar.xml", FileMode.Open, FileAccess.Read, FileShare.Read);86 Car mycar = (Car)formatter.Deserialize(stream);87 stream.Close();88 MessageBox.Show(string.Format("Price of Car: {0},\n Owner:{1}", mycar.Price, mycar.Owner));89 }90 }91}/// <summary> /// 对象序列化,对象必须具有可序列化标记([Serializable]),且有读写方法的公共属性(public) /// </summary> /// <param name="type">对象类型 </param> /// <param name="serialObject"> </param> /// <returns> </returns> public static string Serialization(Type type, object serialObject) { StringBuilder sb = new StringBuilder(); TextWriter writer = new StringWriter(sb); XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, serialObject); string result = sb.ToString().Replace("utf-16", "utf-8"); return result; } /// <summary> /// 对象反序列化 /// </summary> /// <param name="type"> </param> /// <param name="content">xml </param> /// <returns> </returns> public static object Deserialization(Type type, string xmlString) { // XmlTextReader tr = new XmlTextReader(new StringReader(xmlString)); XmlReader reader = XmlReader.Create(new StringReader(xmlString)); XmlSerializer serializer2 = new XmlSerializer(type); return serializer2.Deserialize(reader); } public static MemoryStream Serialize_Binary(object obj) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.AssemblyFormat = FormatterAssemblyStyle.Full; bf.TypeFormat = FormatterTypeStyle.TypesAlways; bf.Serialize(ms, obj); return ms; } public static object Deserialize_Binary(MemoryStream ms) { ms.Seek(0, SeekOrigin.Begin); BinaryFormatter bf = new BinaryFormatter(); bf.AssemblyFormat = FormatterAssemblyStyle.Full; bf.TypeFormat = FormatterTypeStyle.TypesAlways; object obj = bf.Deserialize(ms); return obj; } /// <summary> /// 把对象实例序列化成指定编码的XML字符串 /// </summary> /// <param name="Instance">对象</param> /// <param name="EncodingName">文本编码对象</param> /// <returns></returns> public static string ObjectToXMLByEnCoding( object Instance, Encoding MsgEncoding ) { /// 构造内存流 MemoryStream stream = null; /// 文本流 TextWriter writer = null; /// 序列化结果 string xmlstr = string.Empty; try { stream = new MemoryStream(); writer = new StreamWriter( stream, MsgEncoding ); // get serialise object XmlSerializer serializer = new XmlSerializer( Instance.GetType() ); XmlSerializerNamespaces xsn = new XmlSerializerNamespaces(); xsn.Add( string.Empty, string.Empty ); serializer.Serialize( writer, Instance, xsn ); // 把序列化的字符串通过writer对象写到内存流对象中 int count = ( int )stream.Length; // 获取内存流大小 byte[] arr = new byte[count]; // 构造一个与内存流一样大小的byte数组 stream.Seek( 0, SeekOrigin.Begin ); // 把游标重新指为起始的位置 // 复制内存流数据到byte数组 stream.Read( arr, 0, count ); // 获取指定编码的XML字符串 xmlstr = MsgEncoding.GetString( arr ).Trim(); arr = null; } catch ( Exception ex ) { //记录异常 return ""; } finally { if ( stream != null && stream.Length > 0 ) { stream.Close(); } if ( writer != null ) { writer.Close(); } } return xmlstr; } /// <summary> /// XMLs to object. /// </summary> /// <param name="xml">The XML.</param> /// <param name="t">反序列的类型</param> /// <returns></returns> public static object XMLToObject(string xml, Type t) { StringReader stream = null; XmlTextReader reader = null; Object o = null; try { XmlSerializer serializer = new XmlSerializer(t); stream = new StringReader(xml); // read xml data reader = new XmlTextReader(stream); // create reader // covert reader to object o = serializer.Deserialize(reader); } catch (Exception ex) { //记录异常 } finally { if (stream != null) { stream.Close(); } if (reader != null) { reader.Close(); } } return o; } sqlite3 通过日期取季度 csharp中怎么做多层窗口 怎么链接到Access2007数据库上? 两个datatimepicker控件 怎样计算两个日期间的天数和共经历了哪几个月 请问,怎样得到一个自定义实体的所有属性列表, 关于进销存系统一点不懂想做 各位大吓帮帮我啊!!!!!!! 诸位帮我解决一下吧! WPF,创建用户控件 求助 :将一个java类转为C# 类 类和方法 十万火急,高手救我!
在.net中, IFormatter接口提供了对象序列化的功能。他有两个公有的方法:反序列化对象方法
Deserialize : Deserializes the data on the provided stream and reconstitutes the graph of objects。序列化对象方法
Serialize:Serializes an object, or graph of objects with the given root to the provided stream。我们可以将对象序列化成两种格式:BinaryFormatter :将对象序列化为二进制格式
SoapFormatter:将对象序列化为Soap格式代码://要进行序列化的类
1using System;
2using System.Collections.Generic;
3using System.Text;
4
5namespace SerializeDemos
6{
7 [Serializable]
8 public class Car
9 {
10 private string _Price;
11 private string _Owner;
12 public string Price
13 {
14 get { return this._Price; }
15 set { this._Price = value; }
16 }
17 public string Owner
18 {
19 get { return this._Owner; }
20 set { this._Owner = value; }
21 }
22 public Car(string o, string p)
23 {
24 this.Price = p;
25 this.Owner = o;
26 }
27 }
28}
29
//序列化以及反序列化对象
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Text;
7using System.Windows.Forms;
8using System.IO;
9using System.Runtime.Serialization.Formatters.Binary;
10using System.Runtime.Serialization.Formatters.Soap;
11using System.Xml.Serialization;
12
13
14namespace SerializeDemos
15{
16
17 public partial class Form1 : Form
18 {
19 public Form1()
20 {
21 InitializeComponent();
22 }
23 private void Form1_Load(object sender, EventArgs e)
24 {
25
26 }
27
28 private void button1_Click(object sender, EventArgs e)
29 {
30 Car car = new Car(this.txtOwner.Text, this.txtPrice.Text);
31 FileStream fileStream = new FileStream("SerializedCar.bin", FileMode.Create);
32 // 用二进制格式序列化
33 BinaryFormatter binaryFormatter = new BinaryFormatter();
34 binaryFormatter.Serialize(fileStream, car);
35 fileStream.Close();
36 MessageBox.Show("Successful");
37 }
38
39 private void button2_Click(object sender, EventArgs e)
40 {
41 Car car = new Car(this.txtOwner.Text, this.txtPrice.Text);
42 FileStream fileStream = new FileStream("SerializedCar.Soap", FileMode.Create);
43 // 序列化为Soap
44 SoapFormatter formatter = new SoapFormatter();
45 formatter.Serialize(fileStream, car);
46 fileStream.Close();
47 MessageBox.Show("Successful");
48 }
49
50 private void button3_Click(object sender, EventArgs e)
51 {
52 Car car = new Car(this.txtOwner.Text, this.txtPrice.Text);
53 FileStream fileStream = new FileStream("SerializedCar.xml", FileMode.Create);
54 // 序列化为xml
55 SoapFormatter formatter = new SoapFormatter();
56 formatter.Serialize(fileStream, car);
57 fileStream.Close();
58 MessageBox.Show("Successful");
59 }
60
61 private void button4_Click(object sender, EventArgs e)
62 {
63 System.Runtime.Serialization.IFormatter formatter = new BinaryFormatter();
64 //二进制格式反序列化
65 Stream stream = new FileStream("SerializedCar.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
66 Car mycar = (Car)formatter.Deserialize(stream);
67 stream.Close();
68 MessageBox.Show(string.Format("Price of Car: {0},\n Owner:{1}", mycar.Price, mycar.Owner));
69 }
70
71 private void button5_Click(object sender, EventArgs e)
72 {
73 System.Runtime.Serialization.IFormatter formatter = new SoapFormatter();
74 //Soap格式反序列化
75 Stream stream = new FileStream("SerializedCar.Soap", FileMode.Open, FileAccess.Read, FileShare.Read);
76 Car mycar = (Car)formatter.Deserialize(stream);
77 stream.Close();
78 MessageBox.Show(string.Format("Price of Car: {0},\n Owner:{1}", mycar.Price, mycar.Owner));
79 }
80
81 private void button6_Click(object sender, EventArgs e)
82 {
83 System.Runtime.Serialization.IFormatter formatter = new SoapFormatter();
84 //Xml格式反序列化
85 Stream stream = new FileStream("SerializedCar.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
86 Car mycar = (Car)formatter.Deserialize(stream);
87 stream.Close();
88 MessageBox.Show(string.Format("Price of Car: {0},\n Owner:{1}", mycar.Price, mycar.Owner));
89 }
90 }
91}/// <summary>
/// 对象序列化,对象必须具有可序列化标记([Serializable]),且有读写方法的公共属性(public)
/// </summary>
/// <param name="type">对象类型 </param>
/// <param name="serialObject"> </param>
/// <returns> </returns>
public static string Serialization(Type type, object serialObject)
{
StringBuilder sb = new StringBuilder();
TextWriter writer = new StringWriter(sb);
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, serialObject); string result = sb.ToString().Replace("utf-16", "utf-8");
return result;
}
/// <summary>
/// 对象反序列化
/// </summary>
/// <param name="type"> </param>
/// <param name="content">xml </param>
/// <returns> </returns>
public static object Deserialization(Type type, string xmlString)
{
// XmlTextReader tr = new XmlTextReader(new StringReader(xmlString));
XmlReader reader = XmlReader.Create(new StringReader(xmlString));
XmlSerializer serializer2 = new XmlSerializer(type);
return serializer2.Deserialize(reader);
}
public static MemoryStream Serialize_Binary(object obj)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.AssemblyFormat = FormatterAssemblyStyle.Full;
bf.TypeFormat = FormatterTypeStyle.TypesAlways;
bf.Serialize(ms, obj);
return ms;
}
public static object Deserialize_Binary(MemoryStream ms)
{
ms.Seek(0, SeekOrigin.Begin);
BinaryFormatter bf = new BinaryFormatter();
bf.AssemblyFormat = FormatterAssemblyStyle.Full;
bf.TypeFormat = FormatterTypeStyle.TypesAlways;
object obj = bf.Deserialize(ms);
return obj;
}
/// <summary>
/// 把对象实例序列化成指定编码的XML字符串
/// </summary>
/// <param name="Instance">对象</param>
/// <param name="EncodingName">文本编码对象</param>
/// <returns></returns>
public static string ObjectToXMLByEnCoding( object Instance, Encoding MsgEncoding )
{
/// 构造内存流
MemoryStream stream = null;
/// 文本流
TextWriter writer = null;
/// 序列化结果
string xmlstr = string.Empty; try
{
stream = new MemoryStream();
writer = new StreamWriter( stream, MsgEncoding ); // get serialise object
XmlSerializer serializer = new XmlSerializer( Instance.GetType() ); XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add( string.Empty, string.Empty ); serializer.Serialize( writer, Instance, xsn ); // 把序列化的字符串通过writer对象写到内存流对象中
int count = ( int )stream.Length; // 获取内存流大小
byte[] arr = new byte[count]; // 构造一个与内存流一样大小的byte数组
stream.Seek( 0, SeekOrigin.Begin ); // 把游标重新指为起始的位置
// 复制内存流数据到byte数组
stream.Read( arr, 0, count );
// 获取指定编码的XML字符串
xmlstr = MsgEncoding.GetString( arr ).Trim();
arr = null;
}
catch ( Exception ex )
{
//记录异常
return "";
}
finally
{
if ( stream != null && stream.Length > 0 )
{
stream.Close();
}
if ( writer != null )
{
writer.Close();
}
} return xmlstr;
} /// <summary>
/// XMLs to object.
/// </summary>
/// <param name="xml">The XML.</param>
/// <param name="t">反序列的类型</param>
/// <returns></returns>
public static object XMLToObject(string xml, Type t)
{
StringReader stream = null; XmlTextReader reader = null;
Object o = null;
try
{ XmlSerializer serializer = new XmlSerializer(t);
stream = new StringReader(xml); // read xml data
reader = new XmlTextReader(stream); // create reader // covert reader to object
o = serializer.Deserialize(reader);
}
catch (Exception ex)
{
//记录异常
}
finally
{
if (stream != null)
{
stream.Close();
}
if (reader != null)
{
reader.Close();
}
} return o;
}