c# 对序列化类XMLSerializer 二次封装泛型化方便了一些使用的步骤
原文作者:aircraft
原文链接:https://www.cnblogs.com/DOMLX/p/17270107.html
加工的泛型类如下:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Serialization; namespace Data { public class XMLSerializer<T> { public static bool Save(T obj, string flieName) { string dir = Path.GetDirectoryName(flieName); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); try { if (flieName.Trim().Length == 0) return false; string strFolder = Path.GetDirectoryName(flieName); XmlSerializer xs = new XmlSerializer(typeof(T)); using (FileStream fs = new FileStream(flieName, FileMode.Create)) { xs.Serialize(fs, obj); //fs.Close (); } return true; } catch (Exception ex) { MessageBox.Show("序列化保存时出错,出错原因为:" + ex.ToString()); return false; } } public static T Load(string fileName) { if (File.Exists(fileName) == false) { return default(T); } T obj = default(T); try { XmlSerializer xml = new XmlSerializer(typeof(T)); using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { obj = (T)xml.Deserialize(fs); //fs.Close (); } } catch (Exception ex) { MessageBox.Show("序列化读取时出错,出错原因为:" + ex.ToString()); return default(T); } return obj; } public static T Clone(T target) { T obj = default (T); try { MemoryStream ms = new MemoryStream (); XmlSerializer xml = new XmlSerializer (typeof (T)); xml.Serialize (ms, target); ms.Seek (0, SeekOrigin.Begin); obj = (T)xml.Deserialize (ms); } catch (Exception ex) { MessageBox.Show ("拷贝时出错,出错原因为:" + ex.ToString ()); return default (T); } return obj; } } }
例如我们有个简单的类
class Apply { [CategoryAttribute( "基本参数" ), DisplayName( "片数" )] public int WaferNum { get; set; } = 25; [CategoryAttribute( "基本参数" ), DisplayName( "文件原路径" )] public string OriFilePath { get; set; } = "D:\\Data" ; } |
需要去导入,保存,深拷贝复制,我们就可以这样调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | Apply apply = new Apply(); XMLSerializer<Apply>.Save(apply , "D:\\Appply.xml" ); Apply apply = XMLSerializer<Apply>.Load( "D:\\Appply.xml" ); //也可以作为类的复制快捷方式来使用--例如下面类这样 class App { int a = 0; public App Clone() { App a; a = XMLSerializer<App>.Clone( this ); return a; } } |
若有兴趣交流分享技术,可关注本人公众号,里面会不定期的分享各种编程教程,和共享源码,诸如研究分享关于c/c++,python,前端,后端,opencv,halcon,opengl,机器学习深度学习之类有关于基础编程,图像处理和机器视觉开发的知识
转发和使用本文,请注明作者信息和原文地址---本文原作者为aircraft
---大家好我是徐飞机,有没有大佬们的公司招c++开发/图像处理/opengl/opencv/halcon实习的啊,带上我一个呗QAQ。。。hhhhhh 想要免费获取前端,后端,c/c++,matlab,Python,opencv,机器学习,深度学习,安卓,java,等等全套视频教程请关注机器视觉开发公众号,转发集赞28即可百度云获得hhhhhhhh
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
2018-03-29 手指静脉细化算法过程原理解析 以及python实现细化算法