MakeGenericMethod Reflection 反射 ObjectToXml<T> Generic XmlSerializer


namespace Microshaoft
{
    using System;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    using Microshaoft;
    class Program
    {
        static void Main(string[] args)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            Type[] types = asm.GetTypes().Where
                                            (
                                                t
                                                =>
                                                (t.Namespace == "Entities")
                                            ).ToArray();
            MethodInfo mi = typeof(SerializerHelper).GetMethods().First
                                                                    (
                                                                        m => m.Name.Equals("ObjectToXml") && m.IsGenericMethod && m.GetParameters().Length == 2
                                                                    );
            Parallel.ForEach
                        (
                            types
                            , t
                            =>
                            {
                                Console.WriteLine
                                            (
                                                t.Name
                                            );
                                object o = asm.CreateInstance(t.FullName);
                                string s = (string) mi.MakeGenericMethod(t).Invoke("ObjectToXml", new object[] { o, Encoding.UTF8});
                                Console.WriteLine(s);
                            }
                        );
            Console.ReadLine();
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    //using System.Runtime.Serialization.Formatters.Soap;
    public static class SerializerHelper
    {
        public static T XmlToObject<T>(string Xml)
        {
            StringReader stringReader = new StringReader(Xml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(xmlReader);
        }
        public static string ObjectToXml<T>
                                    (
                                        T Object
                                        , XmlTextWriter writer
                                        , XmlSerializer serializer
                                    )
        {
            serializer.Serialize(writer, Object);
            MemoryStream stream = writer.BaseStream as MemoryStream;
            byte[] bytes = stream.ToArray();
            Encoding e = EncodingHelper.IdentifyEncoding
                                            (
                                                bytes
                                                , Encoding.GetEncoding("gb2312")
                ///                                                , new Encoding[]
                ///                                                        {
                ///                                                            Encoding.UTF8
                ///                                                            , Encoding.Unicode
                ///                                                        }
                                            );
            byte[] buffer = e.GetPreamble();
            int offset = buffer.Length;
            buffer = new byte[bytes.Length - offset];
            Buffer.BlockCopy(bytes, offset, buffer, 0, buffer.Length);
            string s = e.GetString(buffer);
            return s;
        }
        public static string ObjectToXml<T>(T Object, Encoding e)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                XmlTextWriter writer = new XmlTextWriter(stream, e);
                string s = ObjectToXml<T>
                                    (
                                        Object
                                        , writer
                                        , serializer
                                    );
                writer.Close();
                writer = null;
                return s;
            }
        }
        public static byte[] ObjectToBinary<T>
                                    (
                                        T Object
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(stream, Object);
                byte[] buffer = stream.ToArray();
                return buffer;
            }
        }
        public static T BinaryToObject<T>
                                    (
                                        byte[] data
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                stream.Write(data, 0, data.Length);
                stream.Position = 0;
                T Object = (T)formater.Deserialize(stream);
                return Object;
            }
        }
    }
}
namespace Microshaoft
{
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    public static class EncodingHelper
    {
        public static Encoding IdentifyEncoding
                                    (
                                        Stream stream
                                        , Encoding defaultEncoding
                                        , Encoding[] identifyEncodings
                                    )
        {
            byte[] data = StreamDataHelper.ReadDataToBytes(stream);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                            , identifyEncodings
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        Stream stream
                                        , Encoding defaultEncoding
                                    )
        {
            byte[] data = StreamDataHelper.ReadDataToBytes(stream);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        byte[] data
                                        , Encoding defaultEncoding
                                    )
        {
            EncodingInfo[] encodingInfos = Encoding.GetEncodings();
            List<Encoding> list = new List<Encoding>();
            foreach (EncodingInfo info in encodingInfos)
            {
                Encoding e = info.GetEncoding();
                if (e.GetPreamble().Length > 0)
                {
                    list.Add(e);
                    //System.Console.WriteLine(e.EncodingName);
                }
            }
            Encoding[] encodings = new Encoding[list.Count];
            list.CopyTo(encodings);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                            , encodings
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        byte[] data
                                        , Encoding defaultEncoding
                                        , Encoding[] identifyEncodings
                                    )
        {
            Encoding encoding = defaultEncoding;
            foreach (Encoding e in identifyEncodings)
            {
                byte[] buffer = e.GetPreamble();
                int l = buffer.Length;
                if (l == 0)
                {
                    continue;
                }
                bool flag = false;
                for (int i = 0; i < l; i++)
                {
                    if (buffer[i] != data[i])
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    continue;
                }
                else
                {
                    encoding = e;
                }
            }
            return encoding;
        }
    }
}
namespace Microshaoft
{
    using System.IO;
    public static class StreamDataHelper
    {
        public static byte[] ReadDataToBytes(Stream stream)
        {
            byte[] buffer = new byte[64 * 1024];
            MemoryStream ms = new MemoryStream();
            int r = 0;
            int l = 0;
            long position = -1;
            if (stream.CanSeek)
            {
                position = stream.Position;
                stream.Position = 0;
            }
            while (true)
            {
                r = stream.Read(buffer, 0, buffer.Length);
                if (r > 0)
                {
                    l += r;
                    ms.Write(buffer, 0, r);
                }
                else
                {
                    break;
                }
            }
            byte[] bytes = new byte[l];
            ms.Position = 0;
            ms.Read(bytes, 0, (int)l);
            ms.Close();
            ms.Dispose();
            ms = null;
            if (position >= 0)
            {
                stream.Position = position;
            }
            return bytes;
        }
    }
}
namespace Entities
{
    using System;
    /// <summary>
    /// 实体类Transaction
    /// </summary>
    [Serializable]
    public partial class Transaction//: EntityObject
    {
        #region 实体公有属性
        /// <summary>
        /// 交易编号
        /// </summary>
        public string TransactionNO { set; get; }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { set; get; }
        /// <summary>
        /// 描述
        /// </summary>
        public string Description { set; get; }
        /// <summary>
        /// 交易关联的产品ID
        /// </summary>
        public int? ProductId { set; get; }
        /// <summary>
        /// 金额字段
        /// </summary>
        public string AmountField { set; get; }
        /// <summary>
        /// 修改柜员ID
        /// </summary>
        public int? ModifiedTellerId { set; get; }
        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime ModifiedTime { set; get; }
        #endregion 实体公有属性
    }
}

原文地址:https://www.cnblogs.com/Microshaoft/p/2376202.html