//本程序演示了最简单的序列化 和反序列化 ,将对象存储到本地文件中 ,
//对象序列化的另一个目的是网络传输信息
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;
namespace 序列化_啊
{
class Program
{
static void Main(string[] args)
{
//创建文件a.dat
FileStream f = new FileStream("a.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
//创建类的实例t
test t = new test();
//给属性赋值
t.A = "hello";
t.N = 5;
//二进制序列化
IFormatter format = new BinaryFormatter();
format.Serialize(f, t);
f.Close();
//读取文件
f = new FileStream("a.dat", FileMode.Open, FileAccess.Read);
test m = (test)format.Deserialize(f);
Console.WriteLine(m.A);
Console.WriteLine(m.N);
f.Close();
Console.Read();
}
[Serializable]//可序列化标记
class test
{
int n = 0;
string a = null;
[NonSerialized]//不可序列化标记
int b = 10;
public int N
{
set
{
n = value;
}
get
{
return n;
}
}
public string A
{
set
{
a = value;
}
get
{
return a;
}
}
}
}
}
阅读全文
类别:默认分类 查看评论