通過序列化和反序列化泛型數據實體集合來實現持久化數據對象的方法
我們在平時使用數據庫的時候,經常會碰到一個問題,就是不希望數據實體對象插入數據庫中, 卻有想持久化的時候,那么就可以用序列化成
xml字符串,來保存到其他地方,由于生成的是字符串,所以可以保存到任意我們想保存的地方。比如 asp.net的viewstate,cookie,cache等。
首先,我們定義一個數據實體類。
class entity
{
public entity()
{}
private int id;
public int id
{
get
{
return id;
}
set
{
id = value;
}
}
private string name;
public string name
{
get
{
return name;
}
set
{
name = value;
}
}
private double price;
public double price
{
get
{
return price;
}
set
{
price = value;
}
}
}
于是將他插入到list<entity>對象中
list<entity> list = new list<entity>();
entity obj = new entity();
obj.id = 1;
obj.name = "test";
obj.price = 3.23;
list.add(obj);
這樣,一個list<entity>對象就創建成功了,下面我們來將他序列化
public static string serialize<businessobject>(list<businessobject> genericlist)
{
xmldocument result = new xmldocument();
result.loadxml("<root></root>");
foreach (businessobject obj in genericlist)
{
xmlelement item = result.createelement("item");
propertyinfo[] properties = obj.gettype().getproperties();
foreach (propertyinfo property in properties)
{
if (property.getvalue(obj, null) != null)
{
xmlelement element = result.createelement(property.name);
element.setattribute("type", property.propertytype.name);
element.innertext = property.getvalue(obj, null).tostring();
item.appendchild(element);
}
}
result.documentelement.appendchild(item);
}
return result.innerxml;
}
然后我們調用這個方法
string str = serialize<entity>(list);
生成的xml文件為:
<root>
<item>
<id type="int32">1</id>
<name type="string">test</name>
<price type="double">3.23</price>
</item>
</root>
下面,我們根據上面生成的xml文件,將他反序列化,生成剛才的list<entity>對象
public static list<businessobject> deserialize<businessobject>(string xmlstr)
{
list<businessobject> result = new list<businessobject>();
xmldocument xmldoc = new xmldocument();
xmldoc.loadxml(xmlstr);
foreach (xmlnode itemnode in xmldoc.getelementsbytagname("root").item(0).childnodes)
{
businessobject item = activator.createinstance<businessobject>();
propertyinfo[] properties = typeof(businessobject).getproperties();
foreach (xmlnode propertynode in itemnode.childnodes)
{
string name = propertynode.name;
string type = propertynode.attributes["type"].value;
string value = propertynode.innerxml;
foreach (propertyinfo property in properties)
{
if (name == property.name)
{
property.setvalue(item,convert.changetype(value,property.propertytype), null);
}
}
}
result.add(item);
}
return result;
}
然后我們調用這個方法:
list<entity> list = deserialize<entity>(str);
完了。
本文只是給大家介紹了序列化list<>對象的簡單方法,用的時候要根據自己的情況而定。
菜鳥學堂:新聞熱點
疑難解答