教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 c#序列化实例详解

c#序列化实例详解

发布时间:2016-07-26   编辑:jiaochengji.com
分享下c#实现序列化的一篇教程,通过实例详细掌握下c#序列化的知识,有需要的朋友参考下。

所谓序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。
这两个过程结合起来,可以轻松地存储和传输数据。

几种序列化技术:
1)二进制序列化保持类型保真度,这对于在应用程序的不同调用之间保留对象的状态很有用。例如,通过将对象序列化到剪贴板,可在不同的应用程序之间共享对象。您可以将对象序列化到流、磁盘、内存和网络等等。远程处理使用序列化“通过值”在计算机或应用程序域之间传递对象。

2)XML 序列化仅序列化公共属性和字段,且不保持类型保真度。当您要提供或使用数据而不限制使用该数据的应用程序时,这一点是很有用的。由于 XML 是一个开放式标准,因此,对于通过 Web 共享数据而言,这是一个很好的选择。SOAP 同样是一个开放式标准,这使它也成为一个颇具吸引力的选择。

3)使用提供的数据协定,将类型实例序列化和反序列化为 XML 流或文档(或者JSON格式)。常应用于WCF通信。
BinaryFormatter
序列化可被定义为将对象的状态存储到存储媒介中的过程。在此过程中,对象的公共字段和私有字段以及类的名称(包括包含该类的程序集)都被转换为字节流,然后写入数据流。在以后反序列化该对象时,创建原始对象的精确复本。
1、使一个类可序列化的最简单方式是按如下所示使用 Serializable 属性标记。
2、有选择的序列化

通过用 NonSerialized 属性标记成员变量,可以防止它们被序列化
3、自定义序列化
1) 在序列化期间和之后运行自定义方法

最佳也是最简单的方法(在 .Net Framework 2.0 版中引入),就是在序列化期间和之后将下列属性应用于用于更正数据的方法:
OnDeserializedAttribute
OnDeserializingAttribute
OnSerializedAttribute
OnSerializingAttribute

例子:
 

复制代码 代码示例:
// This is the object that will be serialized and deserialized.
[Serializable()] 
public class TestSimpleObject 
{
    // This member is serialized and deserialized with no change.
    public int member1;
    // The value of this field is set and reset during and
    // after serialization.
    private string member2;
    // This field is not serialized. The OnDeserializedAttribute
    // is used to set the member value after serialization.
    [NonSerialized()]
    public string member3;
    // This field is set to null, but populated after deserialization.
    private string member4;
    // Constructor for the class.
    public TestSimpleObject()
    {
  member1 = 11;
  member2 = "Hello World!";
  member3 = "This is a nonserialized value";
  member4 = null;
    }
    public void Print()
    {
  Console.WriteLine("member1 = '{0}'", member1);
  Console.WriteLine("member2 = '{0}'", member2);
  Console.WriteLine("member3 = '{0}'", member3);
  Console.WriteLine("member4 = '{0}'", member4);
    }
    [OnSerializing()]
    internal void OnSerializingMethod(StreamingContext context)
    {
  member2 = "This value went into the data file during serialization.";
    }
    [OnSerialized()]
    internal void OnSerializedMethod(StreamingContext context)
    {
  member2 = "This value was reset after serialization.";
    }
    [OnDeserializing()]
    internal void OnDeserializingMethod(StreamingContext context)
    {
  member3 = "This value was set during deserialization";
    }
    [OnDeserialized()]
    internal void OnDeserializedMethod(StreamingContext context)
    {
  member4 = "This value was set after deserialization.";
    }   
}
 

2) 实现 ISerializable 接口
对于用 Serializable 属性标记且在类级别上或其构造函数上具有声明性或命令性安全的类,不应使用默认序列化。相反,这些类应始终实现 ISerializable 接口。实现 ISerializable 涉及实现 GetObjectData 方法以及在反序列化对象时使用的特殊构造函数。

例子:
 

复制代码 代码示例:
[Serializable]
public class MyObject : ISerializable
{
  public int n1;
  public int n2;
  public String str;
  public MyObject()
  {
  }
  protected MyObject(SerializationInfo info, StreamingContext context)
  {
    n1 = info.GetInt32("i");
    n2 = info.GetInt32("j");
    str = info.GetString("k");
  }
[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter
=true)]
  public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue("i", n1);
    info.AddValue("j", n2);
    info.AddValue("k", str);
  }
}
 

注意:
在反序列化一个对象时不调用构造函数。出于性能方面的原因对反序列化施加了该约束。但是,这违反了运行库与对象编写器之间的一些通常约定,开发人员应确保他们在将对象标记为可序列化时了解其后果。
SoapFormatter
 以 SOAP 格式将对象或整个连接对象的图形序列化和反序列化。基本用法类似于BinaryFormatter。SoapFormatter 和 BinaryFormatter 两个类实现 IRemotingFormatter 接口以支持远程过程调用 (RPC),实现 IFormatter 接口(由 IRemotingFormatter 继承)以支持对象图形的序列化。SoapFormatter 类还支持对 ISoapMessage 对象进行 RPC,而不必使用 IRemotingFormatter 功能。
XmlSerializer
将对象序列化到 XML 文档中和从 XML 文档中反序列化对象。XmlSerializer 使您得以控制如何将对象编码到 XML 中。
XML 序列化是将对象的公共属性 (Property) 和字段转换为序列格式(这里是指 XML)以便存储或传输的过程。反序列化则是从 XML 输出中重新创建原始状态的对象。因此,可以将序列化视为将对象的状态保存到流或缓冲区的方法。例如,ASP.NET 使用 XmlSerializer 类对 XML Web services 消息进行编码。
例子:
 

复制代码 代码示例:
public class MyClass
{
    public MyObject MyObjectProperty;
}
public class MyObject
{
    public string ObjectName;
}
 

序列化后的XML  
 

复制代码 代码示例:
<MyClass>
  <MyObjectProperty>
  <ObjectName>My String</ObjectName>
  </MyObjectProperty>
</MyClass>

还可以通过标记来控制XML的输出
1、默认值
DefaultValueAttribute
2、过滤某属性或字段
 XmlIgnoreAttribute
3、重写默认序列化逻辑
4、将对象序列化为 SOAP 编码的 XML 流
注意
XML 序列化不转换方法、索引器、私有字段或只读属性(只读集合除外)。要序列化对象的所有字段和属性(公共的和私有的),请使用 BinaryFormatter,而不要使用 XML 序列化。
DataContractSerializer
使用提供的数据协定,将类型实例序列化和反序列化为 XML 流或文档。 此类不能被继承。
DataContractSerializer 用于序列化和反序列化在 Windows Communication Foundation (WCF) 消息中发送的数据。 通过将 DataContractAttribute 属性 (Attribute) 应用于类,而将 DataMemberAttribute 属性 (Attribute) 应用于类成员,可以指定要序列化的属性 (Property) 和字段。

使用步骤:
1)DataContractSerializer 与 DataContractAttribute 和 DataMemberAttribute 类结合使用。
要准备序列化某个类,请将 DataContractAttribute 应用于该类。 对于返回要序列化的数据的类的每个成员,请应用 DataMemberAttribute。 您可以序列化字段和属性,而无论其可访问性级别是什么:private、protected、internal、protected internal 或 public。
2)添加到已知类型的集合中
在序列化或反序列化对象时,DataContractSerializer 必须“已知”该类型。 首先,创建一个实现 IEnumerable<T>(如 List<T>)的类实例,并将已知类型添加到集合中。 然后,使用接受 IEnumerable<T>(例如,[M:System.Runtime.Serialization.DataContractSerializer.#ctor(System.Type,System.Collections.Generic.IEnumerable{System.Type}])的重载之一创建 DataContractSerializer 的实例。

例子:
 

复制代码 代码示例:
namespace DataContractSerializerExample
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Xml;
    // You must apply a DataContractAttribute or SerializableAttribute
    // to a class to have it serialized by the DataContractSerializer.
    [DataContract(Name = "Customer", Namespace = "http://www.jbxue.com")]
    class Person : IExtensibleDataObject
    {
  [DataMember()]
  public string FirstName;
  [DataMember]
  public string LastName;
  [DataMember()]
  public int ID;
  public Person(string newfName, string newLName, int newID)
  {
FirstName = newfName;
LastName = newLName;
ID = newID;
  }
  private ExtensionDataObject extensionData_Value;
  public ExtensionDataObject ExtensionData
  {
get
{
    return extensionData_Value;
}
set
{
    extensionData_Value = value;
}
  }
    }
    public sealed class Test
    {
  private Test() { }
  public static void Main()
  {
try
{
    WriteObject("DataContractSerializerExample.xml");
    ReadObject("DataContractSerializerExample.xml");
}
catch (SerializationException serExc)
{
    Console.WriteLine("Serialization Failed");
    Console.WriteLine(serExc.Message);
}
catch (Exception exc)
{
    Console.WriteLine(
    "The serialization operation failed: {0} StackTrace: {1}",
    exc.Message, exc.StackTrace);
}
finally
{
    Console.WriteLine("Press <Enter> to exit....");
    Console.ReadLine();
}
  }
  public static void WriteObject(string fileName)
  {
Console.WriteLine(
    "Creating a Person object and serializing it.");
Person p1 = new Person("Zighetti", "Barbara", 101);
FileStream writer = new FileStream(fileName, FileMode.Create);
DataContractSerializer ser =
    new DataContractSerializer(typeof(Person));
ser.WriteObject(writer, p1);
writer.Close();
  }
  public static void ReadObject(string fileName)
  {
Console.WriteLine("Deserializing an instance of the object.");
FileStream fs = new FileStream(fileName,
FileMode.Open);
XmlDictionaryReader reader =
    XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(Person));
// Deserialize the data and read it from the instance.
Person deserializedPerson =
    (Person)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
Console.WriteLine(String.Format("{0} {1}, ID: {2}",
deserializedPerson.FirstName, deserializedPerson.LastName,
deserializedPerson.ID));
  }
    }
 

DataContractJsonSerializer
将对象序列化为 JavaScript 对象表示法 (JSON),并将 JSON 数据反序列化为对象。 此类不能被继承。

您可能感兴趣的文章:
C#序列化与反序列化的实例详解
c#序列化实例详解
php对象的序列化与反序列化 PHP对象存储与传输
jQuery-serialize()输出序列化form表单值的方法
特色的Python序列解包、链式赋值、链式比较
Python中的56个内置函数详解(七)
php 序列化数组的例子
php 序列化与反序列化的实例详解
python中怎么把列表转成字符串
php常用的魔术函数详细解析

关键词: 序列化   
[关闭]
~ ~