您的位置:首页 > 编程语言 > C#

C# 串行化和反串行化存储数据示例

2014-10-09 17:16 260 查看
可以将对象和结构体转化为某种格式,从而适合网络传输和数据存储(串行化主要完成两个任务:实现WEB服务和将集合对象存储在介质之中)。在.NET中,这个转换过程就成为串行化(Serialization),逆串行化(Deserialization)是串行化的逆过程,可以将串行化流转换为原来的对象或者结构体。

.NET主要支持三种主要的串行化:

1,二进制串行化(Binary),使用BinaryFormatter类,将类型串行化为二进制流。

2,SOAP串行化。使用SoapFormatter类,将类型串行化为遵循简单对象访问协议标准的XML格式。

3,XML串行化,使用XMLSerializer类,将类型串行化为基本的XML,WEB服务就使用这样的串行化。

对类进行XML串行化需要注意以下几点:

(1)该类必须有公共的无参构造函数

(2)只能串行化公共的属性和字段

(3)不能串行化只读的属性

(4)若要串行化定制集合类中的对象,则该类必须从System.Collection.CollectionBase类派生,并包含索引器。

(5)要串行化多个对象,通常最简单的方法是将他们存放在强类型的数组或链表等容器中。

二进制串行化示例:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections;

namespace SerializeDemo
{
/// <summary>
/// 用户信息结构体
/// </summary>
[Serializable]
struct UserInfo
{
public UserInfo(string id,string name,string password)
{
this.id = id;
this.name = name;
this.password = password;
}
string id;
public string Id
{
get { return id; }
}
string name;
public string Name
{
get { return name; }
}
string password;
public string Password
{
get { return password; }
}
}
/// <summary>
/// 商品信息结构体
/// </summary>
[Serializable]
struct Goods
{
public Goods(string id,string name,double price)
{
this.id = id;
this.name = name;
this.price = price;
}
string id;
public string Id
{
get { return id; }
}
string name;
public string Name
{
get { return name; }
}
double price;
public double Price
{
get { return price; }
}

}

class Program
{
static void Main(string[] args)
{
ArrayList arr = new ArrayList();
for (int i = 0; i < 1000; i++)
{
UserInfo info = new UserInfo("Id" + i.ToString(), "Name" + i.ToString(), "PassWord" + i.ToString());
arr.Add(info);
}
for (int i = 0; i < 1000; i++)
{
Goods info = new Goods("Id" + i.ToString(), "Good" + i.ToString(), i);
arr.Add(info);
}

FileStream fs = new FileStream(@"C:\Users\Jessiane\Desktop\data.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, arr);
fs.Close();
arr.Clear();
fs = new FileStream(@"C:\Users\Jessiane\Desktop\data.dat", FileMode.Open);
arr = (ArrayList)bf.Deserialize(fs);
while (true)
{
Console.WriteLine("输入检索名");
string name = Console.ReadLine();
foreach (object o in arr)
{
if (o is Goods)
{
Goods info = (Goods)o;
if (info.Name == name)
{
Console.WriteLine(info.Id.ToString());
}
}
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐