实体序列化反序列化 半成品

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ConsoleApplication15
{
    public static class ListAndDataTableExtension
    {
        public static DataTable ToDataTable<T>(this List<T> list) where T : new()
        {
            DataTable table = new DataTable();
            PropertyInfo[] ps = typeof(T).GetProperties();
            foreach (PropertyInfo p in ps)
            {
                if (!p.PropertyType.IsGenericType)
                {
                    table.Columns.Add(p.Name, p.PropertyType);
                }
                else
                {
                    if (p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        table.Columns.Add(p.Name,Nullable.GetUnderlyingType(p.PropertyType));
                    
                    }
                
                }
            
            }
            foreach (T obj in list)
            {
                DataRow row = table.NewRow();
                foreach (PropertyInfo p in ps)
                {
                    row[p.Name] = p.GetValue(obj);
                }
                table.Rows.Add(row);
            }
            return table;
        }
        public static List<T> ToList<T>(this DataTable table) where T : new()
        {
            List<T> list = new List<T>();
            PropertyInfo[] ps = typeof(T).GetProperties();            
            foreach (DataRow row in table.Rows)
            {
                T obj = new T();
                foreach (DataColumn col in table.Columns)
                {
                    foreach (PropertyInfo p in ps)
                    {
                        if (p.Name == col.ColumnName)
                        {
                            if (!p.PropertyType.IsGenericType)
                            {
                                p.SetValue(obj, string.IsNullOrEmpty(row[p.Name].ToString()) ? null : Convert.ChangeType(row[p.Name], p.PropertyType));
                            }
                            else
                            {
                                if (p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                                {
                                    p.SetValue(obj,string.IsNullOrEmpty(row[p.Name].ToString())?null:Convert.ChangeType(row[p.Name],Nullable.GetUnderlyingType(p.PropertyType)));
                                }
                            }
                        }
                    }
                
                }
                list.Add(obj);
            
            }
            return list;
        
        }
    }
    [DataContract(Name = "Student", Namespace = "123")]
    public class Student
    {
        [DataMember]
        public int? stuNo { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Sex { get; set; }
        [DataMember]
        public int Age { get; set; }
        public override string ToString()
        {
            string s = string.Empty;
            PropertyInfo[] ps = typeof(Student).GetProperties();
            ps.ToList().ForEach(p => { s +=p.Name+":"+ p.GetValue(this).ToString() + " "; });
            return s;
        }
    
    }
    [DataContract(Name = "Teacher", Namespace = "456")]
    public class Teacher
    {
        [DataMember]
        public int? stuNo1 { get; set; }
        [DataMember]
        public string Name1 { get; set; }
        [DataMember]
        public string Sex1 { get; set; }
        [DataMember]
        public int Age1 { get; set; }
        public override string ToString()
        {
            string s = string.Empty;
            PropertyInfo[] ps = typeof(Teacher).GetProperties();
            ps.ToList().ForEach(p => { s += p.Name + ":" + p.GetValue(this).ToString() + " "; });
            return s;
        }

    }
    class Program
    {
        public static List<Student> stuList = new List<Student>();
        static void Main(string[] args)
        {
            for (int i = 1; i <= 10;i++ )
                stuList.Add(new Student() { stuNo = i, Name = i.ToString(), Sex = i.ToString(), Age = i });
            DataTable table = stuList.ToDataTable<Student>();
            List<Student> stus = table.ToList<Student>();
            DataTable table2 = table.Clone();
            foreach (DataRow row in table.Rows)
            {
                DataRow NewRow = table2.NewRow();
                NewRow.ItemArray = row.ItemArray;
                table2.Rows.Add(NewRow);
            }
            DataContractSerializer s = new DataContractSerializer(typeof(Student));
            DataContractSerializer s2 = new DataContractSerializer(typeof(Teacher));
            using (FileStream fs = new FileStream(typeof(Student).Name + ".xml", FileMode.Create))
            {

                s.WriteObject(fs, stus[0]);
            }

            using (FileStream fs = new FileStream(typeof(Student).Name + ".xml", FileMode.Open))
            {
                Student stu = s.ReadObject(fs) as Student;
                Console.WriteLine(stu.ToString());
            }

            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Student));
            ////创建存储区为内存流  
            //FileStream ms = new FileStream(typeof(Student).Name + ".xml", FileMode.Create);
            ////将json字符串写入内存流中  
            //serializer.WriteObject(ms, stus[0]);
            //System.IO.StreamReader reader = new StreamReader(ms);
            //ms.Position = 0;
            //string strRes = reader.ReadToEnd();
            //reader.Close();
            //ms.Close();
            Console.ReadKey();
        }
    }
}

原文地址:https://www.cnblogs.com/kexb/p/4557663.html