/// <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 character
if (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.Value
if (value == DBNull.Value)
{
prop.SetValue(item, prop.PropertyType.IsValueType ? Activator.CreateInstance(prop.PropertyType) : null);
}
else
{
try
{ //Eps类型的属性不需要动态赋值,bug1208201038
if (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#中常用的扩展类
于 2024-08-13 15:37:03 首次发布