zoukankan      html  css  js  c++  java
  • 序列化和反序列化

    代码:

    internal static class Class1
    {
        private static readonly string XML_FOLDER = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
            "CompanyName", "ProjectName");
        private static readonly string XML_FILE = Path.Combine(XML_FOLDER, "config.xml");
    
        static Class1()
        {
            if (!Directory.Exists(XML_FOLDER))
            {
                Directory.CreateDirectory(XML_FOLDER);
            }
        }
    
        internal static T Deserialize<T>()
        {
            return (T)new XmlSerializer(typeof(T)).Deserialize(new FileStream(XML_FILE, FileMode.OpenOrCreate, FileAccess.ReadWrite));
        }
        internal static void Serialize(this object obj)
        {
            new XmlSerializer(obj.GetType()).Serialize(new FileStream(XML_FILE, FileMode.Create, FileAccess.ReadWrite), obj);
        }
    }

    用法:

    new List<string> { "asd", "dfd" }.Serialize();
    var a = Class1.Deserialize<List<string>>();
    internal static class Class3
    {
        private static readonly string XML_FOLDER = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
            "CompanyName", "ProjectName");
        private static readonly string XML_FILE = Path.Combine(XML_FOLDER, "config.xml");
    
        static Class3()
        {
            if (!Directory.Exists(XML_FOLDER))
            {
                Directory.CreateDirectory(XML_FOLDER);
            }
        }
    
        internal static T Deserialize<T>()
        {
            using (var stream = new FileStream(XML_FILE, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                return (T)new XmlSerializer(typeof(T)).Deserialize(stream);
            }
        }
        internal static void Serialize(this object obj)
        {
            using (var stream = new FileStream(XML_FILE, FileMode.Create, FileAccess.ReadWrite))
            {
                new XmlSerializer(obj.GetType()).Serialize(stream, obj);
            }
        }
    }
  • 相关阅读:
    Java数据库小项目02--管家婆项目
    Java数据库小项目01--实现用户登录注册
    Java数据库小项目00---基础知识
    MySQL基础练习02---牛客网
    ICMP
    语法糖
    双绞线
    telnet 时代的 bbs
    ARPA
    IEEE802是一个局域网标准系列
  • 原文地址:https://www.cnblogs.com/yao2yao4/p/3203132.html
Copyright © 2011-2022 走看看