当前位置: 首页 > 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…...

第19节 Node.js Express 框架

Express 是一个为Node.js设计的web开发框架&#xff0c;它基于nodejs平台。 Express 简介 Express是一个简洁而灵活的node.js Web应用框架, 提供了一系列强大特性帮助你创建各种Web应用&#xff0c;和丰富的HTTP工具。 使用Express可以快速地搭建一个完整功能的网站。 Expre…...

【力扣数据库知识手册笔记】索引

索引 索引的优缺点 优点1. 通过创建唯一性索引&#xff0c;可以保证数据库表中每一行数据的唯一性。2. 可以加快数据的检索速度&#xff08;创建索引的主要原因&#xff09;。3. 可以加速表和表之间的连接&#xff0c;实现数据的参考完整性。4. 可以在查询过程中&#xff0c;…...

mongodb源码分析session执行handleRequest命令find过程

mongo/transport/service_state_machine.cpp已经分析startSession创建ASIOSession过程&#xff0c;并且验证connection是否超过限制ASIOSession和connection是循环接受客户端命令&#xff0c;把数据流转换成Message&#xff0c;状态转变流程是&#xff1a;State::Created 》 St…...

对WWDC 2025 Keynote 内容的预测

借助我们以往对苹果公司发展路径的深入研究经验&#xff0c;以及大语言模型的分析能力&#xff0c;我们系统梳理了多年来苹果 WWDC 主题演讲的规律。在 WWDC 2025 即将揭幕之际&#xff0c;我们让 ChatGPT 对今年的 Keynote 内容进行了一个初步预测&#xff0c;聊作存档。等到明…...

Linux离线(zip方式)安装docker

目录 基础信息操作系统信息docker信息 安装实例安装步骤示例 遇到的问题问题1&#xff1a;修改默认工作路径启动失败问题2 找不到对应组 基础信息 操作系统信息 OS版本&#xff1a;CentOS 7 64位 内核版本&#xff1a;3.10.0 相关命令&#xff1a; uname -rcat /etc/os-rele…...

vulnyx Blogger writeup

信息收集 arp-scan nmap 获取userFlag 上web看看 一个默认的页面&#xff0c;gobuster扫一下目录 可以看到扫出的目录中得到了一个有价值的目录/wordpress&#xff0c;说明目标所使用的cms是wordpress&#xff0c;访问http://192.168.43.213/wordpress/然后查看源码能看到 这…...

并发编程 - go版

1.并发编程基础概念 进程和线程 A. 进程是程序在操作系统中的一次执行过程&#xff0c;系统进行资源分配和调度的一个独立单位。B. 线程是进程的一个执行实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。C.一个进程可以创建和撤销多个线程;同一个进程中…...

Kubernetes 节点自动伸缩(Cluster Autoscaler)原理与实践

在 Kubernetes 集群中&#xff0c;如何在保障应用高可用的同时有效地管理资源&#xff0c;一直是运维人员和开发者关注的重点。随着微服务架构的普及&#xff0c;集群内各个服务的负载波动日趋明显&#xff0c;传统的手动扩缩容方式已无法满足实时性和弹性需求。 Cluster Auto…...

Linux安全加固:从攻防视角构建系统免疫

Linux安全加固:从攻防视角构建系统免疫 构建坚不可摧的数字堡垒 引言:攻防对抗的新纪元 在日益复杂的网络威胁环境中,Linux系统安全已从被动防御转向主动免疫。2023年全球网络安全报告显示,高级持续性威胁(APT)攻击同比增长65%,平均入侵停留时间缩短至48小时。本章将从…...

前端调试HTTP状态码

1xx&#xff08;信息类状态码&#xff09; 这类状态码表示临时响应&#xff0c;需要客户端继续处理请求。 100 Continue 服务器已收到请求的初始部分&#xff0c;客户端应继续发送剩余部分。 2xx&#xff08;成功类状态码&#xff09; 表示请求已成功被服务器接收、理解并处…...