基于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
相关推荐
努力的lpp1 小时前
php反序列化一(大白话版)
开发语言·web安全·php·ctf·反序列化
菜鸟~noob2331 小时前
【电子战】第03篇:CFAR(恒虚警)处理【含matlab代码】
开发语言·matlab
lhldsg2 小时前
全民健身解决方案小程序开发:从0到1的技术实战
java·数据库·需求分析
jason成都2 小时前
Spring WebFlux 适配达梦新方案|dm‑r2dbc:Netty 异步传输的实验性 R2DBC 驱动
java·后端·spring
泡海椒2 小时前
内置SPI函数库详解:JQuick-Java Builtin工具类实战用法
java·开发语言·python
hqyjzsb2 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
辰烨chenye2 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
小羊没烦恼!3 小时前
Hello Web API系列教程——Web API与国际化
java·服务器·前端·javascript·php
Keven_113 小时前
算法札记:ACM适用的很骚的C++语法(持续更新)
开发语言·c++
脉动数据行情14 小时前
C# 实现德指 DAX 期货 WebSocket 实时行情监听
开发语言·websocket·c#