• 周六. 8月 20th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

c#字符串序列化-字符串转对象转字符串

admin

11月 28, 2021

c#字符串序列化-字符串转对象转字符串

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace Comdll
{
    public class Serializable_Class
    {
        /// <summary>
        /// 字符串序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToString<T>(T obj)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);
                stream.Position = 0;
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                return Convert.ToBase64String(buffer);
            }
        }
        /// <summary>
        /// 字符串转对象(Base64编码字符串反序列化为对象)
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>对象</returns>
        public static T StringToObject<T>(string str)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                
                byte[] bytes = Convert.FromBase64String(str);
                stream.Write(bytes, 0, bytes.Length);
                stream.Position = 0;
                IFormatter formatter = new BinaryFormatter();
                return (T)formatter.Deserialize(stream);
            }
        }

        /// <summary>
        /// XML序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <param name="o"></param>
        public static void XMLserializer<T>(string name, object o)
        {
            using (FileStream stream = new FileStream(name, FileMode.OpenOrCreate))
            {
                XmlSerializer s = new XmlSerializer(typeof(T));
                s.Serialize(stream, o);
            }
        }
        /// <summary>
        /// XML 反序列化为Repair
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        public static T XmlReserializer<T>(string name)
        {
            using (FileStream stream = new FileStream(name, FileMode.OpenOrCreate))
            {
                XmlSerializer s = new XmlSerializer(typeof(T));
                object o = s.Deserialize(stream);
                return (T)o;
            }
        }

    }
}
欢迎讨论,相互学习。
[email protected]

发表回复

您的电子邮箱地址不会被公开。