今天遇到一个问题就是DataGridViewCellStyle这个类型,我们想对其进行序列化。但是遗憾的是,该类型并没有声明为可序列化。所以,不管我们用哪一个序列化器,都会报告错误。似乎这是一个不可能解决的问题。
经过研究,在.NET 2.0中确实比较难做到,但可以通过.NET 3.0的一个DataContractSerializer来实现。该序列化器是专门为WCF设计的,是XML序列化器的一种。
http://msdn.microsoft.com/zh-cn/vstudio/system.runtime.serialization.datacontractserializer.aspx
下面是一个例子:
创建一个windows Forms程序,选择.NET Framework 为3.0,并要添加System.Runtime.Serialization程序集的引用。
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Runtime.Serialization; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// 序列化 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Serialize_Click(object sender, EventArgs e) { //因为DataGridViewCellStyle的属性有一些特殊类型,所以要预先注册 List<Type> types = new List<Type>(); types.Add(typeof(DBNull)); types.Add(typeof(System.Globalization.CultureInfo)); DataContractSerializer x = new DataContractSerializer(typeof(DataGridViewCellStyle), types); DataGridViewCellStyle style = new DataGridViewCellStyle(); style.BackColor = System.Drawing.Color.Red; FileStream fs = new FileStream("temp.xml", FileMode.Create); x.WriteObject(fs, style); fs.Close(); } /// <summary> /// 反序列化 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeSerialize_Click(object sender, EventArgs e) { List<Type> types = new List<Type>(); types.Add(typeof(DBNull)); types.Add(typeof(System.Globalization.CultureInfo)); DataContractSerializer x = new DataContractSerializer(typeof(DataGridViewCellStyle), types); FileStream fs = new FileStream("temp.xml", FileMode.Open); DataGridViewCellStyle style = (DataGridViewCellStyle)x.ReadObject(fs); fs.Close(); MessageBox.Show(style.BackColor.ToString()); } } }
再深入地看,我们可以用NetDataContractSerializer来实现同样的目的
http://msdn.microsoft.com/zh-cn/vstudio/system.runtime.serialization.netdatacontractserializer.aspx
序列化
DataGridViewCellStyle style = new DataGridViewCellStyle(); style.BackColor = System.Drawing.Color.Red; FileStream fs = new FileStream("temp.xml", FileMode.Create); NetDataContractSerializer x = new NetDataContractSerializer(); x.Serialize(fs, style); fs.Close();
反序列化
FileStream fs = new FileStream("temp.xml", FileMode.Open); NetDataContractSerializer x = new NetDataContractSerializer(); DataGridViewCellStyle style = (DataGridViewCellStyle)x.Deserialize(fs); fs.Close(); MessageBox.Show(style.BackColor.ToString());