C#中常用的扩展类
/// <summary>/// 常用扩展/// </summary>public static class UsualExtension{public static string[] chineseNumbers = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };public static string[] chineseUnits = { "", "十", "百", "千", "万", "亿" };/// <summary> /// 集合是否为空或返回元素个数为0/// </summary>/// <typeparam name="TSource">集合类型</typeparam>/// <param name="source">集合</param>/// <returns></returns>public static bool IsNullorZero<TSource>(this IEnumerable<TSource> source){if (source == null || source.Count() == 0){return true;}return false;}/// <summary>/// 集合转换为object数组/// </summary>/// <typeparam name="TSource">集合类型</typeparam>/// <param name="source">集合</param>/// <returns></returns>public static object[] ToObjectArray<TSource>(this IEnumerable<TSource> source){return Array.ConvertAll<TSource, object>(source.ToArray(), x => (object)x);}/// <summary>/// 集合转换为object集合/// </summary>/// <typeparam name="TSource">集合类型</typeparam>/// <param name="source">集合</param>/// <returns></returns>public static List<object> ToObjectList<TSource>(this IEnumerable<TSource> source){return source.ToObjectArray().ToList();}/// <summary>/// 按分隔符拼接为字符串,(字符串取类型ToString方法)/// </summary>/// <typeparam name="TSource">集合类型</typeparam>/// <param name="source">集合</param>/// <param name="separator">分隔符</param>/// <returns></returns>public static string ToSplitString<T>(this IEnumerable<T> source, string separator = ","){if (source.IsNullorZero()){return string.Empty;}var targetArr = Array.ConvertAll<T, string>(source.ToArray(), x => x.ToString());return string.Join(separator, targetArr);}/// <summary>/// 日期转换成中文格式 例如:2023年7月17日10时25分01秒/// </summary>/// <param name="dt">待转化的时间</param>/// <returns></returns>public static string ConvertDateTimeToCN(this DateTime dt){var result = string.Empty;if (dt != null && dt != WonderFramework.Common.BaseConst.MIN_DATE && dt != DateTime.MinValue){result = dt.ToString("yyyy年MM月dd日HH时mm分ss秒");}return result;}/// <summary>/// 动态对象转换为实体对象/// </summary>/// <typeparam name="T"></typeparam>/// <param name="obj"></param>/// <returns></returns>public static T DynamicToEntity<T>(dynamic obj){string json = JsonConvert.SerializeObject(obj);return JsonConvert.DeserializeObject<T>(json);}/// <summary>/// 阿拉伯数字转中文数字/// </summary>/// <param name="number"></param>/// <returns></returns>/// <exception cref="ArgumentOutOfRangeException"></exception>public static string ConvertToCNNumber(this int number){if (number < 0 || number > 999999999)throw new ArgumentOutOfRangeException("Number out of range");if (number == 0)return chineseNumbers[0];string result = "";int unitIndex = 0;while (number > 0){int digit = number % 10;if (digit != 0){result = chineseNumbers[digit] + chineseUnits[unitIndex] + result;}else{// Add zero only if it's not already the first characterif (result.Length > 0 && result[0] != chineseNumbers[0][0])result = chineseNumbers[digit] + result;}number /= 10;unitIndex++;}return result;}/// <summary>/// 日期时间格式成yyyy-MM-dd HH:mm:ss 格式/// </summary>/// <param name="sourceDate"></param>/// <returns></returns>public static string ToLongDateTimeFormat(this DateTime sourceDate){return sourceDate.ToString("yyyy-MM-dd HH:mm:ss");}/// <summary>/// 日期时间格式成yyyy-MM-dd格式/// </summary>/// <param name="sourceDate"></param>/// <returns></returns>public static string ToShortDateTimeFormat(this DateTime sourceDate){return sourceDate.ToString("yyyy-MM-dd");}/// <summary>/// 通过反射动态给实体某个字段赋值/// </summary>/// <param name="obj">实体对象</param>/// <param name="propertyName">字段名称</param>/// <param name="value">具体值</param>/// <exception cref="ArgumentException"></exception>public static void SetPropertyValue(this object obj, string propertyName, object value){// 获取obj的类型 Type type = obj.GetType();if (string.IsNullOrEmpty(propertyName)){return;}// 获取该类型上名为propertyName的属性 PropertyInfo property = type.GetProperty(propertyName);// 检查属性是否存在且可写 if (property != null && property.CanWrite){// 尝试将值转换为属性的类型(如果需要的话) value = Convert.ChangeType(value, property.PropertyType);// 设置属性值 property.SetValue(obj, value, null);}else{// 属性不存在或不可写,你可以根据需要抛出异常或记录日志 throw new ArgumentException($"Property {propertyName} does not exist or is not writable on object of type {type.Name}.");}}public static List<T> ToEntityList<T>(this DataTable dataTable) where T : new(){var list = new List<T>();var properties = typeof(T).GetProperties();// 创建一个映射字典var mapping = properties.ToDictionary(p => p.Name,p => dataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName).FirstOrDefault(colName => colName.Replace("_", "").ToLower() == p.Name.Replace("_", "").ToLower()));foreach (DataRow row in dataTable.Rows){var item = new T();foreach (var prop in properties){var columnName = mapping[prop.Name];if (columnName != null && row.Table.Columns.Contains(columnName)){var value = row[columnName];// 检查 DBNull.Valueif (value == DBNull.Value){prop.SetValue(item, prop.PropertyType.IsValueType ? Activator.CreateInstance(prop.PropertyType) : null);}else{try{ //Eps类型的属性不需要动态赋值,bug1208201038if (prop.PropertyType.ToString().IndexOf("Eps") >= 0|| prop.PropertyType.ToString().IndexOf("IList") >= 0)continue;Type tempObj = prop.PropertyType;if (tempObj != typeof(System.String) && value == null){continue;}if (tempObj != typeof(System.String) && value.ToString() == ""){continue;}// 特殊类型处理if (prop.PropertyType == typeof(DateTime)){prop.SetValue(item, DateTime.Parse(value.ToString()));}else if (prop.PropertyType == typeof(double)){prop.SetValue(item, double.Parse(value.ToString()));}else if (prop.PropertyType == typeof(int)){prop.SetValue(item, int.Parse(value.ToString()));}else{// 使用 Convert.ChangeType 处理其他类型prop.SetValue(item, Convert.ChangeType(value, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType));}}catch (Exception ex){throw new InvalidOperationException($"Failed to convert property '{prop.Name}' from type '{value?.GetType() ?? typeof(object)}' to '{prop.PropertyType}'", ex);}}}}list.Add(item);}return list;}/// <summary>/// 获取你能提交的天数集合/// </summary>/// <param name="startDay"></param>/// <param name="endDay">采取硬编码 31号</param>/// <returns></returns>public static List<int> GetCanSubmitDaysSimplified(int startDay, int endDay){if (startDay == endDay) // 表示当天{return new List<int> { startDay };}else if (endDay < startDay){// 跨月情况return Enumerable.Range(startDay, 31 - startDay + 1).Concat(Enumerable.Range(1, endDay)).ToList();}else{// 同一个月内return Enumerable.Range(startDay, endDay - startDay + 1).ToList();}}/// <summary>/// 判断数组是否相等/// </summary>/// <typeparam name="T"></typeparam>/// <param name="array1"></param>/// <param name="array2"></param>/// <returns></returns>public static bool AreArraysEqual<T>(T[] array1, T[] array2){if (array1.Length != array2.Length)return false;for (int i = 0; i < array1.Length; i++){if (!array1[i].Equals(array2[i]))return false;}return true;}/// <summary>/// 比较两个实体对象的属性值。/// </summary>/// <typeparam name="T">实体类的类型。</typeparam>/// <param name="entity1">第一个实体对象。</param>/// <param name="entity2">第二个实体对象。</param>/// <returns>如果所有属性值相同返回true,否则返回false并记录不同的属性。</returns>public static Tuple<bool, Dictionary<string, Tuple<object, object>>> CompareEntities<T>(T entity1, T entity2)where T : class{var propertyDifferences = new Dictionary<string, Tuple<object, object>>();bool isEqual = true;foreach (var property in typeof(T).GetProperties()){// 检查属性上是否有 [WonderProperty] 注解var hasWonderPropertyAttribute = property.GetCustomAttribute<WonderPropertyAttribute>() != null;if (hasWonderPropertyAttribute){var value1 = property.GetValue(entity1);var value2 = property.GetValue(entity2);if ((value1 == null && value2 != null) || (value1 != null && value2 == null) || (value1 != null && !value1.Equals(value2))){propertyDifferences.Add(property.Name, Tuple.Create(value1, value2));isEqual = false;}}}return Tuple.Create(isEqual, propertyDifferences);}}```相关文章:
C#中常用的扩展类
/// <summary>/// 常用扩展/// </summary>public static class UsualExtension{public static string[] chineseNumbers { "零", "一", "二", "三", "四", "五", "六", "七", &…...
麒麟v10(ky10.x86_64)升级——openssl-3.2.2、openssh-9.8p1
系统版本: ky10.x86_64 下载安装包并上传 openssh下载地址 https://cdn.openbsd.org/pub/OpenBSD/OpenSSH/portable openssl下载地址 https://openssl-library.org/source/index.html zlib下载地址 https://zlib.net/fossils/ 上传安装包 备份配置文件 cp -r /etc/ssh /et…...
【Unity】有限状态机和抽象类多态
一、介绍 有限状态机是一个用来进行对象状态管理的计算模型。它由一组状态、一个或者多个触发事件以及状态之间的转换条件所组成。 对于任意一个游戏对象,我们可以为其编写一个或者多个状态机,使其能够在不同状态下有不同的决策和运作机制。 核心思想…...
KETTLE调用http传输中文参数的问题
场景:检查服务器异常(hive)服务,就通过http发送一条短信到手机上,内容类似:【通知】 S T A R T D A T E h i v e 服务检测异常 {START_DATE}_hive服务检测异常 STARTDATEhive服务检测异常{DB_ID}&#…...
Gaussian Splatting 在 Ubuntu22.04 下部署
代码:graphdeco-inria/gaussian-splatting (github) 论文:[2308.04079] 3D Gaussian Splatting for Real-Time Radiance Field Rendering (arxiv.org) 1. 禁用自带驱动 Nouveau Ubuntu 自带的显卡驱动,是非Nvida官方版。在后面装cuda的时候,会报驱动不兼容问题。 1.进入…...
ppt中添加页码(幻灯片编号)及问题解决方案
在幻灯片母版中,选择插入 幻灯片编号 右下角显示幻灯片编号 问题一:母版中没有显示编号 原因可能是母版版式中没有设置显示,勾选即可。 问题二:子母版中没有显示幻灯片 将母版中的编号复制到子母版中。 问题三:应用…...
Flutter 初识:对话框和弹出层
Flutter对话框和弹出层小结 对话框AlertDialog属性解析 showDialog属性解析示例 SimpleDialog示例 AboutDialog属性解析示例 Custom Full-Screen Dialog示例 带动画效果的CustomDialog(showGeneralDialog)属性解析示例 自定义Dialog属性解析示例 输入对话…...
启程与远征Ⅳ--人工智能革命尚未发生
人工智能有望彻底改变工作场所。到目前为止,已经有人工智能工具可以取代或增强每一项工作,并使生产力飞速提升。甚至有许多人预测,文案写作等整个行业将在未来几年内被人工智能工具完全取代。但是,如果你抛开炒作,看看…...
Python教程(十五):IO 编程
目录 专栏列表引言基础概念什么是IO? 同步IO vs 异步IO同步IO(Synchronous IO)异步IO(Asynchronous IO) Python中的IO标准IO标准输入和输出 文件IO文件操作的上下文管理器打开文件读取文件操作内存中的数据 高级文件操…...
Qt窗口交互场景、子窗口数据获取
一、前言 在现代软件开发中,图形用户界面(GUI)的设计不仅仅关乎美观,更在于用户体验和功能的无缝衔接。Qt框架以其强大的跨平台能力和丰富的组件库,成为众多开发者构建GUI应用的首选工具。在Qt应用中,窗口…...
【C++学习笔记 18】C++中的隐式构造函数
举个例子 #include <iostream> #include <string>using String std::string;class Entity{ private:String m_Name;int m_Age; public:Entity(const String& name):m_Name(name), m_Age(-1) {}Entity(int age) : m_Name("UnKnown"), m_Age(age) {}…...
单元训练01:LED指示灯的基本控制
蓝桥杯 小蜜蜂 单元训练01:LED指示灯的基本控制 #include "stc15f2k60s2.h" #include <intrins.h>#define LED(x) \{ \P2 P2 & 0x1f | 0x80; \P0 x; \P2 & 0x1f; \}…...
Sanic 和 Go Echo 对比
💝💝💝欢迎莅临我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:「storm…...
内部排序(插入、交换、选择)
一、排序的部分基本概念 1. 算法的稳定性 若待排序表中有两个元素 Ri 和 Rj ,其对应的关键字相同即 keyi keyj,且在排序前 Ri 在 Rj 的前面,若使用某一排序算法排序后,Ri 仍然在 Rj 的前面,则称这个排序算法是稳定的…...
Vue3的多种组件通信方式
父组件向子组件传递数据 (Props) 父组件 <template><child :name"name"></child> </template><script setup> import { ref } from vue import Child from ./Child.vueconst name ref(小明) </script> 子组件 <template…...
【C++语言】list的构造函数与迭代器
1. list的介绍及使用 1.1 list的介绍 list的文档介绍 1. list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。 2. list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点…...
Python 安装 PyTorch详细教程
本章教程,介绍如何安装PyTorch,介绍两种安装方式,一种是通过pip直接安装,一种是通过conda方式安装。 一、查看CUDA版本 二、安装PyTorch 1、pip安装方式 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu1162、conda安装方式 …...
html页面缩放自适应
html页面缩放自适应 一、为什么页面要进行缩放自适应 在我们一般web端进行页面拼接完成后,在web端的显示正常(毕竟我们是按照web端进行页面拼接完成的),那么要是用其他设备打开呢,比如手机或者平板,这时候…...
024.自定义chormium-修改屏幕尺寸
自定义chormium-修改屏幕尺寸 屏幕尺寸信息雷同太大,用作指纹信息,作用不多。 但多个类似小信息组合在一起的话,也就是成唯一指纹了。积少成多吧。 一、如何使用js获取屏幕信息 将下面的代码复制进F12控制台 console.log("screen.widt…...
测试环境搭建整套大数据系统(十九:kafka3.6.0单节点做 sasl+acl)
1. 增加配置配文件信息 vim /opt/kafka_2.13-3.6.1/config/server.properties listenersPLAINTEXT://192.168.50.240:9092,OUTER://192.168.50.240:9094# Listener name, hostname and port the broker will advertise to clients. # If not set, it uses the value for &quo…...
Keil 中设置 STM32 Flash 和 RAM 地址详解
文章目录 Keil 中设置 STM32 Flash 和 RAM 地址详解一、Flash 和 RAM 配置界面(Target 选项卡)1. IROM1(用于配置 Flash)2. IRAM1(用于配置 RAM)二、链接器设置界面(Linker 选项卡)1. 勾选“Use Memory Layout from Target Dialog”2. 查看链接器参数(如果没有勾选上面…...
Cloudflare 从 Nginx 到 Pingora:性能、效率与安全的全面升级
在互联网的快速发展中,高性能、高效率和高安全性的网络服务成为了各大互联网基础设施提供商的核心追求。Cloudflare 作为全球领先的互联网安全和基础设施公司,近期做出了一个重大技术决策:弃用长期使用的 Nginx,转而采用其内部开发…...
论文浅尝 | 基于判别指令微调生成式大语言模型的知识图谱补全方法(ISWC2024)
笔记整理:刘治强,浙江大学硕士生,研究方向为知识图谱表示学习,大语言模型 论文链接:http://arxiv.org/abs/2407.16127 发表会议:ISWC 2024 1. 动机 传统的知识图谱补全(KGC)模型通过…...
在WSL2的Ubuntu镜像中安装Docker
Docker官网链接: https://docs.docker.com/engine/install/ubuntu/ 1、运行以下命令卸载所有冲突的软件包: for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do sudo apt-get remove $pkg; done2、设置Docker…...
Linux 中如何提取压缩文件 ?
Linux 是一种流行的开源操作系统,它提供了许多工具来管理、压缩和解压缩文件。压缩文件有助于节省存储空间,使数据传输更快。本指南将向您展示如何在 Linux 中提取不同类型的压缩文件。 1. Unpacking ZIP Files ZIP 文件是非常常见的,要在 …...
从面试角度回答Android中ContentProvider启动原理
Android中ContentProvider原理的面试角度解析,分为已启动和未启动两种场景: 一、ContentProvider已启动的情况 1. 核心流程 触发条件:当其他组件(如Activity、Service)通过ContentR…...
LOOI机器人的技术实现解析:从手势识别到边缘检测
LOOI机器人作为一款创新的AI硬件产品,通过将智能手机转变为具有情感交互能力的桌面机器人,展示了前沿AI技术与传统硬件设计的完美结合。作为AI与玩具领域的专家,我将全面解析LOOI的技术实现架构,特别是其手势识别、物体识别和环境…...
MySQL 主从同步异常处理
阅读原文:https://www.xiaozaoshu.top/articles/mysql-m-s-update-pk MySQL 做双主,遇到的这个错误: Could not execute Update_rows event on table ... Error_code: 1032是 MySQL 主从复制时的经典错误之一,通常表示ÿ…...
机器学习的数学基础:线性模型
线性模型 线性模型的基本形式为: f ( x ) ω T x b f\left(\boldsymbol{x}\right)\boldsymbol{\omega}^\text{T}\boldsymbol{x}b f(x)ωTxb 回归问题 利用最小二乘法,得到 ω \boldsymbol{\omega} ω和 b b b的参数估计$ \boldsymbol{\hat{\omega}}…...
深度解析:etcd 在 Milvus 向量数据库中的关键作用
目录 🚀 深度解析:etcd 在 Milvus 向量数据库中的关键作用 💡 什么是 etcd? 🧠 Milvus 架构简介 📦 etcd 在 Milvus 中的核心作用 🔧 实际工作流程示意 ⚠️ 如果 etcd 出现问题会怎样&am…...
