□通过序列化和反序列化泛型数据实体集合来实...... 通过序列化和反序列化泛型数据实体集合来实现持久化数据对象的方法 我们在平时使用数据库的时候,经常会碰到一个问题,就是不希望数据实体对象插入数据库中, 却有想持久化的时候,那么就可以用序列化成 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 List Entity obj = new Entity(); obj.Id = 1; obj.Name = "test"; obj.Price = 3.23; list.Add(obj); 这样,一个List public static string Serialize { XmlDocument result = new XmlDocument(); result.LoadXml(" 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 生成的XML文件为: 下面,我们根据上面生成的xml文件,将他反序列化,生成刚才的List public static List { List XmlDocument XmlDoc = new XmlDocument(); XmlDoc.LoadXml(XmlStr); foreach (XmlNode ItemNode in XmlDoc.GetElementsByTagName("Root").Item(0).ChildNodes) { BusinessObject item = Activator.CreateInstance 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 完了。 本文只是给大家介绍了序列化List<>对象的简单方法,用的时候要根据自己的情况而定。 |
|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )
GMT+8, 2024-9-29 19:22 , Processed in 0.341967 second(s), 12 queries , Gzip On, MemCache On.
Powered by Discuz! X3.5
© 2001-2023 Discuz! Team.