当前位置: 首页 > 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);}}```
http://www.lryc.cn/news/425348.html

相关文章:

  • 麒麟v10(ky10.x86_64)升级——openssl-3.2.2、openssh-9.8p1
  • 【Unity】有限状态机和抽象类多态
  • KETTLE调用http传输中文参数的问题
  • Gaussian Splatting 在 Ubuntu22.04 下部署
  • ppt中添加页码(幻灯片编号)及问题解决方案
  • Flutter 初识:对话框和弹出层
  • 启程与远征Ⅳ--人工智能革命尚未发生
  • Python教程(十五):IO 编程
  • Qt窗口交互场景、子窗口数据获取
  • 【C++学习笔记 18】C++中的隐式构造函数
  • 单元训练01:LED指示灯的基本控制
  • Sanic 和 Go Echo 对比
  • 内部排序(插入、交换、选择)
  • Vue3的多种组件通信方式
  • 【C++语言】list的构造函数与迭代器
  • Python 安装 PyTorch详细教程
  • html页面缩放自适应
  • 024.自定义chormium-修改屏幕尺寸
  • 测试环境搭建整套大数据系统(十九:kafka3.6.0单节点做 sasl+acl)
  • 小白零基础学数学建模应用系列(五):任务分配问题优化与求解
  • 怎么防止源代码泄露?十种方法杜绝源代码泄密风险
  • uniapp left right 的左右模态框
  • Docker Compose与私有仓库部署
  • Layout 布局组件快速搭建
  • 北京城市图书馆-非遗文献馆:OLED透明拼接屏的璀璨应用
  • OpenCV图像滤波(12)图像金字塔处理函数pyrDown()的使用
  • css如何使一个盒子水平垂直居中
  • 机器人等方向学习和研究的目标
  • 封装一个细粒度的限流器
  • 【Spring Boot - 注解】@ResponseBody 注解:处理 JSON 响应