该篇文章是我于2009年6月10日通过自己编写的工具,批量从位于在博客园的博客站点(http://chenxizhang.cnblogs.com)同步而来。文章中的图片地址仍然是链接到博客园的。特此说明! 陈希章原文地址:http://www.cnblogs.com/chenxizhang/archive/2008/09/07/1286345.html原文标题:单向序列化 原文发表:2008/9/7 12:25:00 |
今天遇到一个问题就是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();
}
///
/// 序列化
///
///
///
private void Serialize_Click(object sender, EventArgs e)
{
//因为DataGridViewCellStyle的属性有一些特殊类型,所以要预先注册
List
types =
new List
();
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();
}
///
/// 反序列化
///
///
///
private
void DeSerialize_Click(
object sender, EventArgs e)
{
List
types =
new List
();
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());
作者:陈希章 出处:http://blog.youkuaiyun.com/chen_xizhang 本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |