网上关于对象的序列化与反序列化文章很多,但都是把对象序列化之后保存到文件的,或者从文件里反序列化成对象。但很多数据实体对象我们要求把它保存到数据库,需要将对象序列化之后转成字符串。下面的例子就是将对象序列化之后返回字符串,或者根据字符串反序化成对象
代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.ComponentModel;
namespace DigInfo.Engine
{
public class ColumnTemplateCollection:ICollection<ColumnTemplate>
{
private List<ColumnTemplate> list;
public ColumnTemplateCollection()
{
list = new List<ColumnTemplate>();
}
#region 索引器
public ColumnTemplate this[int index]
{
get
{
if (index < 0)
{
throw new Exception("集合索引不能为负数!");
}
if (index < list.Count)
{
return list[index];
}
else
{
throw new Exception("集合索引超出范围!");
}
}
}
public ColumnTemplate this[string Name]
{
get
{
foreach (ColumnTemplate c in list)
{
if (c.Name.ToLower() == Name.ToLower())
{
return c;
}
}
return null;
}
}
#endregion
#region 序列化
/// <summary>
/// 序列化对象
/// </summary>
/// <returns></returns>
public string Serialize()
{
XmlSerializer serializer = new XmlSerializer(typeof(ColumnTemplateCollection));
MemoryStream stream = new MemoryStream();
serializer.Serialize(stream, this);
StreamReader reader = new StreamReader(stream);
string str = Encoding.UTF8.GetString(stream.GetBuffer());
reader.Close();
return str;
}
/// <summary>
/// 反序列化对象
/// </summary>
/// <param name="xml"></param>
public void Deserialize(string xml)
{
if (string.IsNullOrEmpty(xml))
{
return;
}
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
XmlSerializer serializer = new XmlSerializer(typeof(ColumnTemplateCollection));
ColumnTemplateCollection templates = (ColumnTemplateCollection)serializer.Deserialize(stream);
list.Clear();
foreach (ColumnTemplate c in templates)
{
list.Add(c);
}
}
#endregion
public BindingList<ColumnTemplate> BindingList()
{
BindingList<ColumnTemplate> items = new BindingList<ColumnTemplate>();
foreach (ColumnTemplate c in list)
{
items.Add(c);
}
return items;
}
#region ICollection<ColumnTemplate> 成员
public void Add(ColumnTemplate item)
{
if (Contains(item.Name))
{
throw new Exception("已经存在相同的列名!");
}
list.Add(item);
}
public void Clear()
{
list.Clear();
}
public bool Contains(ColumnTemplate item)
{
return list.Contains(item);
}
public bool Contains(string columnName)
{
if (string.IsNullOrEmpty(columnName))
{
return false;
}
foreach (ColumnTemplate c in list)
{
if (c.Name.ToLower() == columnName.ToLower())
{
return true;
}
}
return false;
}
public void CopyTo(ColumnTemplate[] array, int arrayIndex)
{
list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return list.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(ColumnTemplate item)
{
return list.Remove(item);
}
#endregion
#region IEnumerable<ColumnTemplate> 成员
public IEnumerator<ColumnTemplate> GetEnumerator()
{
return list.GetEnumerator();
}
#endregion
#region IEnumerable 成员
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
#endregion
}
}