您的当前位置:首页正文

利用反射实现序列化和反序列化

2024-11-20 来源:个人技术集锦

主程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Reflection;
using System.Xml;
using 用户自定义输入;

namespace ProtoBuf
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入想要创建的Person类数量:");
            int ListNumber = Convert.ToInt32(Console.ReadLine());
            var list = InitData(ListNumber);
            List<Person> NewList = new List<Person>();
            MemoryStream stream = new MemoryStream();
            TestSerialize(stream, list, NewList);
            Console.Read();
        }

        private static List<Person> InitData(int listCount)
        {
            List<Person> list = new List<Person>();
            for (var i = 0; i < listCount; i++)       //i < 1024*100;
            {
                var person = new Person
                {
                    Sno = i,
                    Name = "Name" + i,
                    Age = i,
                    NowTime = System.DateTime.Now,
                    IsInShool = true,
                    Country = 1,
                    Language = i,
                    Professional = i,
                    Study = 123,
                    FatherName = i,
                    MotherName = "motherName" + i
                };
                list.Add(person);
            }
            return list;
        }

        static void TestSerialize(MemoryStream Stream, List<Person> list, List<Person> Newlist)
        {
            //定义测试次数和统计时间
            int count = 20;
            double time1 = 0, time2 = 0;

            //测试序列化
            Stopwatch PS = new Stopwatch();
            for (int i = 0; i < count; i++)
            {
                PS.Start();
                Serialize(Stream, list);
                PS.Stop();
                time1 += PS.Elapsed.TotalMilliseconds;
            }
            Console.WriteLine("序列化20次平均用时" + time1 / count);

            //测试序列化输出
            //Test.PrintStream(Stream);

            //测试反序列化
            Stopwatch dePS = new Stopwatch();
            for (int j = 0; j < count; j++)
            {
                dePS.Start();
                DeSerialize(Newlist, Stream);
                dePS.Stop();
                time2 += dePS.Elapsed.TotalMilliseconds;
            }
            Console.WriteLine("反序列化20次平均用时" + time2 / count);

            //测试反序列化输出
            //Test.PrintDeSerialize(Newlist);
        }

        static void Serialize(MemoryStream ms, List<Person> list)
        {
            foreach (var obj in list)
            {
                SerializerHelper.Serializa<Person>(ms, obj);
            }
        }

        static void DeSerialize(List<Person> list,MemoryStream ms)
        {
             SerializerHelper.DeSerializa<Person>(list, ms);
        }
    }

    public class Person
    {
        public long Sno { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime NowTime { get; set; }
        public bool IsInShool { get; set; }
        public byte Country { get; set; }
        public decimal Language { get; set; }
        public double Professional { get; set; }
        public short Study { get; set; }
        public float FatherName { get; set; }
        public string MotherName { get; set; }
    }
}

  

序列化和反序列化实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace 用户自定义输入
{
    public class SerializerHelper
    {
        public static void Serializa<T>(MemoryStream ms, T obj)
        {
            BinaryWriter bw = new BinaryWriter(ms);
            PropertyInfo[] props = obj.GetType().GetProperties();
            foreach (PropertyInfo property in props)
            {
                bw.Write(property.Name);
                switch (property.PropertyType.FullName)
                {
                    case "System.String":
                        bw.Write(Convert.ToString(property.GetValue(obj, null)));
                        break;
                    case "System.Int16":
                        bw.Write(Convert.ToInt16(property.GetValue(obj, null)));
                        break;
                    case "System.Int32":
                        bw.Write(Convert.ToInt32(property.GetValue(obj, null)));
                        break;
                    case "System.Int64":
                        bw.Write(Convert.ToInt64(property.GetValue(obj, null)));
                        break;
                    case "System.Boolean":
                        bw.Write(Convert.ToBoolean(property.GetValue(obj, null)));
                        break;
                    case "System.Byte":
                        bw.Write(Convert.ToByte(property.GetValue(obj, null)));
                        break;
                    case "System.Decimal":
                        bw.Write(Convert.ToDecimal(property.GetValue(obj, null)));
                        break;
                    case "System.Double":
                        bw.Write(Convert.ToDouble(property.GetValue(obj, null)));
                        break;
                    case "System.SByte":
                        bw.Write(Convert.ToSByte(property.GetValue(obj, null)));
                        break;
                    case "System.Single":
                        bw.Write(Convert.ToSingle(property.GetValue(obj, null)));
                        break;
                    case "System.UInt16":
                        bw.Write(Convert.ToUInt16(property.GetValue(obj, null)));
                        break;
                    case "System.UInt32":
                        bw.Write(Convert.ToUInt32(property.GetValue(obj, null)));
                        break;
                    case "System.UInt64":
                        bw.Write(Convert.ToUInt64(property.GetValue(obj, null)));
                        break;
                    case "System.DateTime":
                        bw.Write(property.GetValue(obj, null).ToString());
                        break;
                }
            }
        }

        public static void DeSerializa<T>(List<T> list, MemoryStream ms)
        {
            ms.Seek(0, SeekOrigin.Begin);
            BinaryReader br = new BinaryReader(ms);
            PropertyInfo[] fields = typeof(T).GetProperties();
            do
            {
                T obj = Activator.CreateInstance<T>();
                foreach (PropertyInfo field in fields)
                {
                    if (field.Name == br.ReadString())
                    {
                        switch (field.PropertyType.FullName)
                        {
                            case "System.String":
                                field.SetValue(obj, br.ReadString(), null);
                                break;
                            case "System.Int16":
                                field.SetValue(obj, br.ReadInt16(), null);
                                break;
                            case "System.Int32":
                                field.SetValue(obj, br.ReadInt32(), null);
                                break;
                            case "System.Int64":
                                field.SetValue(obj, br.ReadInt64(), null);
                                break;
                            case "System.Boolean":
                                field.SetValue(obj, br.ReadBoolean(), null);
                                break;
                            case "System.Byte":
                                field.SetValue(obj, br.ReadByte(), null);
                                break;
                            case "System.Char":
                                field.SetValue(obj, br.ReadChar(), null);
                                break;
                            case "System.Decimal":
                                field.SetValue(obj, br.ReadDecimal(), null);
                                break;
                            case "System.Double":
                                field.SetValue(obj, br.ReadDouble(), null);
                                break;
                            case "System.SByte":
                                field.SetValue(obj, br.ReadSByte(), null);
                                break;
                            case "System.Single":
                                field.SetValue(obj, br.ReadSingle(), null);
                                break;
                            case "System.UInt16":
                                field.SetValue(obj, br.ReadUInt16(), null);
                                break;
                            case "System.UInt32":
                                field.SetValue(obj, br.ReadInt32(), null);
                                break;
                            case "System.UInt64":
                                field.SetValue(obj, br.ReadInt64(), null);
                                break;
                            case "System.DateTime":
                                field.SetValue(obj, DateTime.Parse(br.ReadString()), null);
                                break;
                        }
                    }
                }
                list.Add(obj);
            } while (br.PeekChar() != -1);
        }
       
    }
}

  测试程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace 用户自定义输入
{
    class Test
    {
        //测试list<Person>是否已经被写入到MemoryStream
        public static void PrintStream(MemoryStream stream)
        {
            Console.WriteLine("测试list<Person>是否已经被写入到MemoryStream");
            stream.Seek(0, SeekOrigin.Begin);
            BinaryReader Test = new BinaryReader(stream);
            for (int i = 0; i <= 100; i++)
            {
                Console.WriteLine(Test.ReadString());
            }
        }

        //测试MemoryStream中的内容是否写入到新的list<Person>
        public static void PrintDeSerialize<T>(List<T> list)
        {
            foreach (T t in list)
            {
                Console.WriteLine("测试MemoryStream中的内容是否写入到Newlist<Person>");
                PropertyInfo[] props = t.GetType().GetProperties();
                foreach (PropertyInfo property in props)
                {
                    Console.WriteLine(property.Name);
                    Console.WriteLine(property.GetValue(t, null));
                }
            }
        }
    }
}

  

转载于:https://www.cnblogs.com/Freedom0619/p/4151266.html

显示全文