Serializable序列化
来源:互联网 发布:windows to go制作方法 编辑:程序博客网 时间:2024/06/03 16:46
C# Serializable
System.SerializableAttribute
串行化是指存储和获取磁盘文件、内存或其他地方中的对象。在串行化时,所有的实例数据都保存到存储介质上,在取消串行化时,对象会被还原,且不能与其原实例区别开来。
只需给类添加Serializable属性,就可以实现串行化实例的成员。
并行化是串行化的逆过程,数据从存储介质中读取出来,并赋给类的实例变量。
例:
1 [Serializable]
2 public class Person
3 {
4 public Person()
5 {
6 }
7
8 public int Age;
9 public int WeightInPounds;
10 }
2 public class Person
3 {
4 public Person()
5 {
6 }
7
8 public int Age;
9 public int WeightInPounds;
10 }
下面来看一个小例子,首先要添加命名空间
using System.Runtime.Serialization.Formatters.Binary;
下面的代码将对象Person进行序列化并存储到一个文件中
1 Person me = new Person();
2
3 me.Age = 34;
4 me.WeightInPounds = 200;
5
6 Stream s = File.Open("Me.dat",FileMode.Create);
7
8 BinaryFormatter bf = new BinaryFormatter();
9
10 bf.Serialize(s,me);
11
12 s.Close();
2
3 me.Age = 34;
4 me.WeightInPounds = 200;
5
6 Stream s = File.Open("Me.dat",FileMode.Create);
7
8 BinaryFormatter bf = new BinaryFormatter();
9
10 bf.Serialize(s,me);
11
12 s.Close();
然后再举一个并行化的例子
Stream s = File.Open("Me.dat",FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
object o = bf.Deserialize(s);
Person p = o as Person;
if(p != null)
Console.WriteLine("DeSerialized Person aged:{0} whight:{1}",p.Age,p.WeightInPounds);
s.Close();
BinaryFormatter bf = new BinaryFormatter();
object o = bf.Deserialize(s);
Person p = o as Person;
if(p != null)
Console.WriteLine("DeSerialized Person aged:{0} whight:{1}",p.Age,p.WeightInPounds);
s.Close();
如果需要对部分字段序列化部分不序列化时,我们可以按照如下设置实现
[Serializable]
public class Person
{
public Person()
{
}
public int Age;
[NonSerialized]
public int WeightInPounds;
}
public class Person
{
public Person()
{
}
public int Age;
[NonSerialized]
public int WeightInPounds;
}
0 0
- Serializable java序列化
- java序列化-Serializable
- Serializable java序列化
- Serializable java序列化
- Serializable java序列化
- 初探序列化---Serializable
- JAVA序列化Serializable
- Serializable java序列化
- 初探序列化---Serializable
- 序列化---,Serializable
- 序列化[Serializable]
- 序列化---Serializable
- Serializable - 序列化
- serializable 序列化
- java序列化Serializable
- Serializable - 序列化
- Serializable java序列化
- Serializable java序列化
- 完全分布式hadoop集群安装之三:hadoop集群配置
- Hibernate4之二级缓存配置
- Spring 3 MVC hello world example
- [org.jeecgframework.core.common.exception.MyExceptionHandler]com.thoughtworks.xstream.mapper.CannotR
- apache svn集成ldap认证
- Serializable序列化
- rails mysql mongoid carrierware gridfs 实现图片上传功能
- Memcached使用整理
- iOS- 绘图教程
- 括号匹配问题
- Swing 中 JTextField事件 与 鼠标事件整合
- leetcode_Gas Station
- SimpleAdapter
- MongoDB GridFS 数据读取效率 benchmark