序列化: 把类存在文件中。
反序列化:把文件中的信息读取到类中。
这也是我很肤浅的理解。 主要是实用。
首先谈一下很重要的一张图。
| XML | SOAP | 二进制 | |
| 序列化器类 | XmlSerializer | SoapFormatter | BinaryFormatter |
| SerializableAttribute 标记 | 不需要 | 需要 | |
| ISerializable 接口 | 不需要实现,实现了也不起作用。 | 可以不实现,但实现了就起作用。 | |
| 无参构造函数 | 必须有,系统提供的缺省无参构造函数也算。 | 不需要,因为反序列化时不调用构造函数。 | |
| 被序列化的数据成员 | 公共属性和字段 | 所有 | |
| 产生文件大小 | 大 | 大 | 小 |
xml的序列化 将类存在XML文件上面去。
public static BaseConfigInfo GetRealBaseConfig()
{
BaseConfigInfo newBaseConfig = null;
string filename = null;
HttpContext context = HttpContext.Current;
if (context != null)
filename = context.Server.MapPath("~/LabelPrint/test1.config");
else
filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config/HLT.config");
try
{
newBaseConfig = (BaseConfigInfo)ConfigFileManager.DeserializeInfo(filename, typeof(BaseConfigInfo));
}
catch
{
newBaseConfig = null;
}
if (newBaseConfig == null)
{
throw new Exception("发生错误: 网站Config目录下没有正确的HLT.config文件");
}
return newBaseConfig;
}
写一下类的形成
[Serializable]
public class BaseConfigInfo
{
public BaseConfigInfo() { }
public EmailConfigInfo EmailConfigInfo
{
get;
set;
}
public SystemConfigInfo SystemConfigInfo
{ get; set; }
}
二进制的序列化
实现序列化和反序列化
需要引用的命名空间
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
对同一个类进行Soap 序列化
需要的命名空间
using System.Runtime.Serialization.Formatters.Soap;
还需要add System.Runtime.Serialization.Formatters.Soap.dll