基于C#的工业测控软件-依赖库

张开发
2026/5/1 13:27:52 15 分钟阅读

分享文章

基于C#的工业测控软件-依赖库
目录简介设计特点实战案例JSON 序列化封装内存序列化文件序列化使用例子使用案例总结简介采用依赖抽象与实现分离的设计模式核心是对第三方库进行封装与适配。设计特点接口隔离每个模块都以 Impl 结尾的文件作为具体实现上层业务只需依赖抽象接口不直接依赖第三方库。可替换性如果未来需要更换 JSON / 日志 / YAML 库比如从 Newtonsoft.Json 切换到 System.Text.Json只需替换 Impl 实现无需修改业务代码。依赖管理每个模块都有独立的 依赖项 节点便于版本控制和冲突排查。文件 / 内存双模式NewtonJson 和 YamlDotNet 都提供了文件操作与内存操作两种实现适配不同场景需求。实战案例JSON 序列化封装NewtonJsonImpl.cs内存操作实现Serialize(object): string将对象序列化为 JSON 字符串Deserialize(string): T将 JSON 字符串反序列化为指定类型对象public interface ICxJson { /// summary /// 对象序列化为 JSON 字符串 /// /summary string Serialize(object obj); /// summary /// JSON 字符串反序列化为对象 /// /summary T DeserializeT(string json) where T : class; }内存序列化using Newtonsoft.Json; using Newtonsoft.Json.Converters; public class NewtonJsonImpl : ICxJson { // 全局复用序列化器提升性能 private static readonly JsonSerializer _serializer; static NewtonJsonImpl() { _serializer new JsonSerializer { // 格式化缩进 Formatting Formatting.Indented, // 忽略空值 NullValueHandling NullValueHandling.Ignore }; // 枚举 → 字符串 _serializer.Converters.Add(new StringEnumConverter()); } public string Serialize(object obj) { if (obj null) throw new ArgumentNullException(nameof(obj)); using var sw new StringWriter(); _serializer.Serialize(sw, obj); return sw.ToString(); } public T DeserializeT(string json) where T : class { if (string.IsNullOrWhiteSpace(json)) throw new ArgumentException(JSON 字符串不能为空); using var sr new StringReader(json); return _serializer.Deserialize(sr, typeof(T)) as T; } }文件序列化using Newtonsoft.Json; using Newtonsoft.Json.Converters; public class NewtonJsonFileImpl : ICxJsonFile { private static readonly JsonSerializer _serializer; static NewtonJsonFileImpl() { _serializer new JsonSerializer { Formatting Formatting.Indented, NullValueHandling NullValueHandling.Ignore }; _serializer.Converters.Add(new StringEnumConverter()); } public void Serialize(object obj, string filePath) { if (obj null) throw new ArgumentNullException(nameof(obj)); if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException(文件路径不能为空); try { using var fs File.CreateText(filePath); _serializer.Serialize(fs, obj); } catch (Exception ex) { throw new InvalidOperationException($JSON 写入文件失败{filePath}, ex); } } public T DeserializeT(string filePath) where T : class { if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException(文件路径不能为空); if (!File.Exists(filePath)) throw new FileNotFoundException(文件不存在, filePath); try { using var fs File.OpenText(filePath); return _serializer.Deserialize(fs, typeof(T)) as T; } catch (Exception ex) { throw new InvalidOperationException($JSON 读取文件失败{filePath}, ex); } } }使用例子// 1. 内存操作 ICxJson json new NewtonJsonImpl(); string jsonStr json.Serialize(new User { Id 1, Name 张三 }); User user json.DeserializeUser(jsonStr); // 2. 文件操作 ICxJsonFile jsonFile new NewtonJsonFileImpl(); jsonFile.Serialize(user, user.json); User userFromFile jsonFile.DeserializeUser(user.json); public class User { public int Id { get; set; } public string Name { get; set; } }NewtonJsonFileImpl.cs文件操作实现Serialize(object, string): void将对象序列化为 JSON 并写入指定文件Deserialize(string): T从指定文件读取 JSON 并反序列化为指定类型对象使用案例using System; using System.IO; using CxBaseSupply; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace CxDepends { /// summary /// Newtonsoft.Json 文件操作实现类 /// 实现 ICxJsonFile 接口对象 ↔ JSON 文件 /// /summary public class NewtonJsonFileImpl : ICxJsonFile { /// summary /// 静态全局序列化器全局复用提升性能 /// /summary private static readonly JsonSerializer _jsonSerializer; /// summary /// 静态构造一次性配置序列化规则 /// /summary static NewtonJsonFileImpl() { _jsonSerializer new JsonSerializer(); // 枚举 → 字符串不转数字 _jsonSerializer.Converters.Add(new StringEnumConverter()); // 格式化缩进文件可读性更强 _jsonSerializer.Formatting Formatting.Indented; // 忽略空值属性 _jsonSerializer.NullValueHandling NullValueHandling.Ignore; } /// summary /// 将对象序列化为 JSON 并写入文件 /// /summary /// param nameobj要序列化的对象/param /// param namefile文件路径/param public void Serialize(object obj, string file) { // 参数校验 if (obj null) throw new ArgumentNullException(nameof(obj), 序列化对象不能为空); if (string.IsNullOrWhiteSpace(file)) throw new ArgumentException(文件路径不能为空, nameof(file)); try { // 创建文件流using 自动释放 using (StreamWriter sw File.CreateText(file)) { _jsonSerializer.Serialize(sw, obj); } } catch (Exception ex) { throw new InvalidOperationException($JSON 写入文件失败{file}, ex); } } /// summary /// 从文件读取 JSON 并反序列化为对象 /// /summary /// typeparam nameT目标类型/typeparam /// param namefile文件路径/param /// returns强类型对象/returns public T DeserializeT(string file) where T : class { // 参数校验 if (string.IsNullOrWhiteSpace(file)) throw new ArgumentException(文件路径不能为空, nameof(file)); if (!File.Exists(file)) throw new FileNotFoundException(JSON 文件不存在, file); try { using (StreamReader sr File.OpenText(file)) { return _jsonSerializer.Deserialize(sr, typeof(T)) as T; } } catch (Exception ex) { throw new InvalidOperationException($JSON 反序列化失败{file}, ex); } } } }总结一句话记住所有依赖作用Newtonsoft.Json 操作 JSONSerilog 记录日志YamlDotNet 操作 YAML

更多文章