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

目录

简介

设计特点

实战案例

[JSON 序列化封装](#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
      {
      ///


      /// 对象序列化为 JSON 字符串
      ///

      string Serialize(object obj);

      复制代码
      /// <summary>
      /// JSON 字符串反序列化为对象
      /// </summary>
      T Deserialize<T>(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 Deserialize<T>(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 Deserialize<T>(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.Deserialize<User>(jsonStr);

// 2. 文件操作
ICxJsonFile jsonFile = new NewtonJsonFileImpl();
jsonFile.Serialize(user, "user.json");
User userFromFile = jsonFile.Deserialize<User>("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 name="obj">要序列化的对象</param>
        /// <param name="file">文件路径</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 name="T">目标类型</typeparam>
        /// <param name="file">文件路径</param>
        /// <returns>强类型对象</returns>
        public T Deserialize<T>(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 = 操作 JSON
  • Serilog = 记录日志
  • YamlDotNet = 操作 YAML
相关推荐
折哥的程序人生 · 物流技术专研2 小时前
第4篇:Lambda 简化策略模式(Java 8+)
java·设计模式·策略模式·函数式编程·lambda·代码简化·扩充系列
researcher-Jiang3 小时前
高性能计算之OpenMP——超算习堂学习1
android·java·学习
西门吹-禅5 小时前
java springboot N+1问题
java·开发语言·spring boot
DLYSB_5 小时前
生命通道:如何用 HIS 医疗系统直连网络声光终端,打造“零延误”的危急值响应网关?
java·网络·数据库·报警灯
skywalk81635 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
weixin_BYSJ19875 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
AI小码5 小时前
LLM 应用的缓存工程:当每次 API 调用都在燃烧成本
java·人工智能·spring·计算机·llm·编程·api
Hui Baby6 小时前
Spring Security
java·后端·spring
IT笔记6 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
2zcode7 小时前
免费开源项目文档:基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn