仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 654|回复: 8
打印 上一主题 下一主题

[学习教程] ASP.NET网站制作之经由过程序列化和反序列化泛型数据实体汇合...

[复制链接]
因胸联盟 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-16 22:47:23 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
归根到底,Java跨平台可以,但是要重新编写代码,否则还分什么J2EE/J2SE/J2ME呢!工具|汇合|数据经由过程序列化和反序列化泛型数据实体汇合来完成耐久化数据工具的办法
我们在平常利用数据库的时分,常常会碰着一个成绩,就是不但愿数据实体工具拔出数据库中,却有想耐久化的时分,那末就能够用序列化成
XML字符串,来保留到其他中央,因为天生的是字符串,以是能够保留就任意我们想保留的中央。好比asp.net的ViewState,cookie,cache等。
起首,我们界说一个数据实体类。
classEntity
{
publicEntity()
{}
privateintid;
publicintId
{
get
{
returnid;
}
set
{
id=value;
}
}
privatestringname;
publicstringName
{
get
{
returnname;
}
set
{
name=value;
}
}
privatedoubleprice;
publicdoublePrice
{
get
{
returnprice;
}
set
{
price=value;
}
}
}

因而将他拔出到List<Entity>工具中
List<Entity>list=newList<Entity>();
Entityobj=newEntity();
obj.Id=1;
obj.Name="test";
obj.Price=3.23;
list.Add(obj);
如许,一个List<Entity>工具就创立乐成了,上面我们来将他序列化
publicstaticstringSerialize<BusinessObject>(List<BusinessObject>GenericList)
{
XmlDocumentresult=newXmlDocument();
result.LoadXml("<Root></Root>");
foreach(BusinessObjectobjinGenericList)
{
XmlElementItem=result.CreateElement("Item");
PropertyInfo[]properties=obj.GetType().GetProperties();
foreach(PropertyInfopropertyinproperties)
{
if(property.GetValue(obj,null)!=null)
{
XmlElementelement=result.CreateElement(property.Name);
element.SetAttribute("Type",property.PropertyType.Name);
element.InnerText=property.GetValue(obj,null).ToString();
Item.AppendChild(element);
}
}
result.DocumentElement.AppendChild(Item);
}
returnresult.InnerXml;
}
然后我们挪用这个办法
stringstr=Serialize<Entity>(list);
天生的XML文件为:
<Root>
<Item>
<IdType="Int32">1</Id>
<NameType="String">test</Name>
<PriceType="Double">3.23</Price>
</Item>
</Root>
上面,我们依据下面天生的xml文件,将他反序列化,天生方才的List<Entity>工具
publicstaticList<BusinessObject>Deserialize<BusinessObject>(stringXmlStr)
{
List<BusinessObject>result=newList<BusinessObject>();
XmlDocumentXmlDoc=newXmlDocument();
XmlDoc.LoadXml(XmlStr);
foreach(XmlNodeItemNodeinXmlDoc.GetElementsByTagName("Root").Item(0).ChildNodes)
{
BusinessObjectitem=Activator.CreateInstance<BusinessObject>();
PropertyInfo[]properties=typeof(BusinessObject).GetProperties();
foreach(XmlNodepropertyNodeinItemNode.ChildNodes)
{
stringname=propertyNode.Name;
stringtype=propertyNode.Attributes["Type"].Value;
stringvalue=propertyNode.InnerXml;
foreach(PropertyInfopropertyinproperties)
{
if(name==property.Name)
{
property.SetValue(item,Convert.ChangeType(value,property.PropertyType),null);
}
}
}
result.Add(item);
}
returnresult;
}
然后我们挪用这个办法:
List<Entity>list=Deserialize<Entity>(str);
完了。
本文只是给人人先容了序列化List工具的复杂办法,用的时分要依据本人的情形而定。
在CSDN里搜索一下“初学”两字,竟有三百余篇帖子(也许更多)。有些帖子说,有了asp的基础,只要15天就能很熟悉了,我甚感自己的愚钝。更多帖子是向大家请教初学者适合看书。两个多月的时间(当然平常杂事比较多。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-6-11 19:59

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表