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

C#编程总结(一)序列化

2015-09-02 23:43 483 查看

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.";
}
}

[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);
}
}

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.contoso.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 数据反序列化为对象。 此类不能被继承。

具体使用与DataContractSerializer类似。这里不再赘述。

下面对这些方法的使用做了汇总,希望能给大家带来一些帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;

namespace SerializerSample
{
/// <summary>
/// 序列化帮助类
/// </summary>
public sealed class SerializeHelper
{
#region DataContract序列化
/// <summary>
/// DataContract序列化
/// </summary>
/// <param name="value"></param>
/// <param name="knownTypes"></param>
/// <returns></returns>
public static string SerializeDataContract(object value, List<Type> knownTypes = null)
{
DataContractSerializer dataContractSerializer = new DataContractSerializer(value.GetType(), knownTypes);

using (MemoryStream ms = new MemoryStream())
{
dataContractSerializer.WriteObject(ms, value);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
/// <summary>
/// DataContract反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T DeserializeDataContract<T>(string xml)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
#endregion

#region DataContractJson序列化
/// <summary>
///  DataContractJson序列化
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string SerializeDataContractJson(object value)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(value.GetType());
using (MemoryStream ms = new MemoryStream())
{
dataContractSerializer.WriteObject(ms, value);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
///  DataContractJson反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="str"></param>
/// <returns></returns>
public static object DeserializeDataContractJson(Type type, string str)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(type);
using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str)))
{
return dataContractSerializer.ReadObject(ms);
}
}
/// <summary>
/// DataContractJson反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public T DeserializeDataContractJson<T>(string json)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)dataContractSerializer.ReadObject(ms);
}
}
#endregion

#region XmlSerializer序列化
/// <summary>
/// 将对象序列化到 XML 文档中和从 XML 文档中反序列化对象。XmlSerializer 使您得以控制如何将对象编码到 XML 中。
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string SerializeXml(object value)
{
XmlSerializer serializer = new XmlSerializer(value.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.Serialize(ms, value);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
/// <summary>
///  XmlSerializer反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="str"></param>
/// <returns></returns>
public static object DeserializeXml(Type type, string str)
{
XmlSerializer serializer = new XmlSerializer(type);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
using (MemoryStream ms = new MemoryStream(bytes))
{
return serializer.Deserialize(ms);
}
}
#endregion

#region BinaryFormatter序列化
/// <summary>
/// BinaryFormatter序列化
/// 必须类型必须标记为Serializable
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializeBinaryFormatter(object obj)
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
formatter.Serialize(ms,obj);
byte[] bytes = ms.ToArray();
obj = formatter.Deserialize(new MemoryStream(bytes));
//如果是UTF8格式,则反序列化报错。可以用Default格式,不过,建议还是传参为byte数组比较好
return Encoding.Default.GetString(bytes);
}
}

/// <summary>
/// BinaryFormatter反序列化
/// 必须类型必须标记为Serializable
/// </summary>
/// <param name="serializedStr"></param>
/// <returns></returns>
public static T DeserializeBinaryFormatter<T>(string serializedStr)
{
BinaryFormatter formatter = new BinaryFormatter();
byte[] bytes = Encoding.Default.GetBytes(serializedStr);
using (MemoryStream ms = new MemoryStream(bytes))
{
return (T)formatter.Deserialize(ms);
}
}
#endregion

#region SoapFormatter序列化
/// <summary>
/// SoapFormatter序列化
/// 必须类型必须标记为Serializable
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializeSoapFormatter(object obj)
{
SoapFormatter formatter = new SoapFormatter();
using (MemoryStream ms = new MemoryStream())
{
formatter.Serialize(ms, obj);
byte[] bytes = ms.ToArray();
return Encoding.UTF8.GetString(bytes);
}
}
/// <summary>
/// SoapFormatter反序列化
/// 必须类型必须标记为Serializable
/// </summary>
/// <param name="serializedStr"></param>
/// <returns></returns>
public static T DeserializeSoapFormatter<T>(string serializedStr)
{
SoapFormatter formatter = new SoapFormatter();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(serializedStr)))
{
return (T)formatter.Deserialize(ms);
}
}
#endregion
}
}


具体的实例代码如下:

下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: