当前位置: 首页 > 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++ 面试 - 基础题】每日 3 题(十九)
  • 【AI】智力即服务
  • 【Redis集群】集群原理最全解析
  • C++——list列表容器经典案例——手机按销量降序排列,若销量相同则按价格降序排列
  • 从阻塞来聊聊mysql的 排他锁 共享锁 mvcc乐观锁;间隙锁;
  • 目标检测之数据增强
  • 探索Ubuntu网络监控:安装与使用流行工具的指南
  • 外部排序(败者树、置换-选择排序、最佳归并树)
  • Xilinx FPGA在线升级——汇总
  • <keep-alive> 一分钟了解
  • Datawhale-动手学CV-Pytorch-MNIST分类实战代码解读
  • 浏览器后门:保护影子 IT 的新前线
  • JAVA maven pom下载失败问题处理
  • [译] 理解数组在 PHP 内部的实现(给PHP开发者的PHP源码-第四部分)
  • CAP理论的例子讲解
  • Cookie 在前端中的实践
  • create-react-app项目添加less配置
  • express.js的介绍及使用
  • extjs4学习之配置
  • github从入门到放弃(1)
  • java架构面试锦集:开源框架+并发+数据结构+大企必备面试题
  • MYSQL如何对数据进行自动化升级--以如果某数据表存在并且某字段不存在时则执行更新操作为例...
  • Otto开发初探——微服务依赖管理新利器
  • python3 使用 asyncio 代替线程
  • Spark in action on Kubernetes - Playground搭建与架构浅析
  • v-if和v-for连用出现的问题
  • vue-router的history模式发布配置
  • Vue组件定义
  • WebSocket使用
  • 工作手记之html2canvas使用概述
  • 开源地图数据可视化库——mapnik
  • 前端技术周刊 2019-01-14:客户端存储
  • 前端临床手札——文件上传
  • 通过来模仿稀土掘金个人页面的布局来学习使用CoordinatorLayout
  • 职业生涯 一个六年开发经验的女程序员的心声。
  • # SpringBoot 如何让指定的Bean先加载
  • #### golang中【堆】的使用及底层 ####
  • #【QT 5 调试软件后,发布相关:软件生成exe文件 + 文件打包】
  • #Spring-boot高级
  • #微信小程序(布局、渲染层基础知识)
  • $$$$GB2312-80区位编码表$$$$
  • (51单片机)第五章-A/D和D/A工作原理-A/D
  • (AtCoder Beginner Contest 340) -- F - S = 1 -- 题解
  • (Bean工厂的后处理器入门)学习Spring的第七天
  • (附源码)ssm跨平台教学系统 毕业设计 280843
  • (四)【Jmeter】 JMeter的界面布局与组件概述
  • (四)汇编语言——简单程序
  • (微服务实战)预付卡平台支付交易系统卡充值业务流程设计
  • (一)appium-desktop定位元素原理
  • (一)使用IDEA创建Maven项目和Maven使用入门(配图详解)
  • ****** 二十三 ******、软设笔记【数据库】-数据操作-常用关系操作、关系运算
  • .NET 快速重构概要1
  • .NET程序集编辑器/调试器 dnSpy 使用介绍