当前位置: 首页 > news >正文

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】有限状态机和抽象类多态

一、介绍 有限状态机是一个用来进行对象状态管理的计算模型。它由一组状态、一个或者多个触发事件以及状态之间的转换条件所组成。 对于任意一个游戏对象&#xff0c;我们可以为其编写一个或者多个状态机&#xff0c;使其能够在不同状态下有不同的决策和运作机制。 核心思想…...

KETTLE调用http传输中文参数的问题

场景&#xff1a;检查服务器异常&#xff08;hive&#xff09;服务&#xff0c;就通过http发送一条短信到手机上&#xff0c;内容类似&#xff1a;【通知】 S T A R T D A T E h i v e 服务检测异常 {START_DATE}_hive服务检测异常 STARTD​ATEh​ive服务检测异常{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中添加页码(幻灯片编号)及问题解决方案

在幻灯片母版中&#xff0c;选择插入 幻灯片编号 右下角显示幻灯片编号 问题一&#xff1a;母版中没有显示编号 原因可能是母版版式中没有设置显示&#xff0c;勾选即可。 问题二&#xff1a;子母版中没有显示幻灯片 将母版中的编号复制到子母版中。 问题三&#xff1a;应用…...

Flutter 初识:对话框和弹出层

Flutter对话框和弹出层小结 对话框AlertDialog属性解析 showDialog属性解析示例 SimpleDialog示例 AboutDialog属性解析示例 Custom Full-Screen Dialog示例 带动画效果的CustomDialog&#xff08;showGeneralDialog&#xff09;属性解析示例 自定义Dialog属性解析示例 输入对话…...

启程与远征Ⅳ--人工智能革命尚未发生

人工智能有望彻底改变工作场所。到目前为止&#xff0c;已经有人工智能工具可以取代或增强每一项工作&#xff0c;并使生产力飞速提升。甚至有许多人预测&#xff0c;文案写作等整个行业将在未来几年内被人工智能工具完全取代。但是&#xff0c;如果你抛开炒作&#xff0c;看看…...

Python教程(十五):IO 编程

目录 专栏列表引言基础概念什么是IO&#xff1f; 同步IO vs 异步IO同步IO&#xff08;Synchronous IO&#xff09;异步IO&#xff08;Asynchronous IO&#xff09; Python中的IO标准IO标准输入和输出 文件IO文件操作的上下文管理器打开文件读取文件操作内存中的数据 高级文件操…...

Qt窗口交互场景、子窗口数据获取

一、前言 在现代软件开发中&#xff0c;图形用户界面&#xff08;GUI&#xff09;的设计不仅仅关乎美观&#xff0c;更在于用户体验和功能的无缝衔接。Qt框架以其强大的跨平台能力和丰富的组件库&#xff0c;成为众多开发者构建GUI应用的首选工具。在Qt应用中&#xff0c;窗口…...

【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&#xff1a;LED指示灯的基本控制 #include "stc15f2k60s2.h" #include <intrins.h>#define LED(x) \{ \P2 P2 & 0x1f | 0x80; \P0 x; \P2 & 0x1f; \}…...

Sanic 和 Go Echo 对比

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐&#xff1a;「storm…...

内部排序(插入、交换、选择)

一、排序的部分基本概念 1. 算法的稳定性 若待排序表中有两个元素 Ri 和 Rj &#xff0c;其对应的关键字相同即 keyi keyj&#xff0c;且在排序前 Ri 在 Rj 的前面&#xff0c;若使用某一排序算法排序后&#xff0c;Ri 仍然在 Rj 的前面&#xff0c;则称这个排序算法是稳定的…...

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是可以在常数范围内在任意位置进行插入和删除的序列式容器&#xff0c;并且该容器可以前后双向迭代。 2. list的底层是双向链表结构&#xff0c;双向链表中每个元素存储在互不相关的独立节点中&#xff0c;在节点…...

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端进行页面拼接完成后&#xff0c;在web端的显示正常&#xff08;毕竟我们是按照web端进行页面拼接完成的&#xff09;&#xff0c;那么要是用其他设备打开呢&#xff0c;比如手机或者平板&#xff0c;这时候…...

024.自定义chormium-修改屏幕尺寸

自定义chormium-修改屏幕尺寸 屏幕尺寸信息雷同太大&#xff0c;用作指纹信息&#xff0c;作用不多。 但多个类似小信息组合在一起的话&#xff0c;也就是成唯一指纹了。积少成多吧。 一、如何使用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…...

C++初阶-list的底层

目录 1.std::list实现的所有代码 2.list的简单介绍 2.1实现list的类 2.2_list_iterator的实现 2.2.1_list_iterator实现的原因和好处 2.2.2_list_iterator实现 2.3_list_node的实现 2.3.1. 避免递归的模板依赖 2.3.2. 内存布局一致性 2.3.3. 类型安全的替代方案 2.3.…...

【Linux】shell脚本忽略错误继续执行

在 shell 脚本中&#xff0c;可以使用 set -e 命令来设置脚本在遇到错误时退出执行。如果你希望脚本忽略错误并继续执行&#xff0c;可以在脚本开头添加 set e 命令来取消该设置。 举例1 #!/bin/bash# 取消 set -e 的设置 set e# 执行命令&#xff0c;并忽略错误 rm somefile…...

练习(含atoi的模拟实现,自定义类型等练习)

一、结构体大小的计算及位段 &#xff08;结构体大小计算及位段 详解请看&#xff1a;自定义类型&#xff1a;结构体进阶-CSDN博客&#xff09; 1.在32位系统环境&#xff0c;编译选项为4字节对齐&#xff0c;那么sizeof(A)和sizeof(B)是多少&#xff1f; #pragma pack(4)st…...

P3 QT项目----记事本(3.8)

3.8 记事本项目总结 项目源码 1.main.cpp #include "widget.h" #include <QApplication> int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); } 2.widget.cpp #include "widget.h" #include &q…...

从零开始打造 OpenSTLinux 6.6 Yocto 系统(基于STM32CubeMX)(九)

设备树移植 和uboot设备树修改的内容同步到kernel将设备树stm32mp157d-stm32mp157daa1-mx.dts复制到内核源码目录下 源码修改及编译 修改arch/arm/boot/dts/st/Makefile&#xff0c;新增设备树编译 stm32mp157f-ev1-m4-examples.dtb \stm32mp157d-stm32mp157daa1-mx.dtb修改…...

【git】把本地更改提交远程新分支feature_g

创建并切换新分支 git checkout -b feature_g 添加并提交更改 git add . git commit -m “实现图片上传功能” 推送到远程 git push -u origin feature_g...

CRMEB 框架中 PHP 上传扩展开发:涵盖本地上传及阿里云 OSS、腾讯云 COS、七牛云

目前已有本地上传、阿里云OSS上传、腾讯云COS上传、七牛云上传扩展 扩展入口文件 文件目录 crmeb\services\upload\Upload.php namespace crmeb\services\upload;use crmeb\basic\BaseManager; use think\facade\Config;/*** Class Upload* package crmeb\services\upload* …...

安宝特案例丨Vuzix AR智能眼镜集成专业软件,助力卢森堡医院药房转型,赢得辉瑞创新奖

在Vuzix M400 AR智能眼镜的助力下&#xff0c;卢森堡罗伯特舒曼医院&#xff08;the Robert Schuman Hospitals, HRS&#xff09;凭借在无菌制剂生产流程中引入增强现实技术&#xff08;AR&#xff09;创新项目&#xff0c;荣获了2024年6月7日由卢森堡医院药剂师协会&#xff0…...

深度学习水论文:mamba+图像增强

&#x1f9c0;当前视觉领域对高效长序列建模需求激增&#xff0c;对Mamba图像增强这方向的研究自然也逐渐火热。原因在于其高效长程建模&#xff0c;以及动态计算优势&#xff0c;在图像质量提升和细节恢复方面有难以替代的作用。 &#x1f9c0;因此短时间内&#xff0c;就有不…...

【C++进阶篇】智能指针

C内存管理终极指南&#xff1a;智能指针从入门到源码剖析 一. 智能指针1.1 auto_ptr1.2 unique_ptr1.3 shared_ptr1.4 make_shared 二. 原理三. shared_ptr循环引用问题三. 线程安全问题四. 内存泄漏4.1 什么是内存泄漏4.2 危害4.3 避免内存泄漏 五. 最后 一. 智能指针 智能指…...