731 lines
17 KiB
C#
731 lines
17 KiB
C#
using NaiBa.Util.Helper;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Runtime.Serialization.Formatters.Binary;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace NaiBa.Util.Extension
|
|
{
|
|
public static partial class Extensions
|
|
{
|
|
#region 转换为long
|
|
/// <summary>
|
|
/// 将object转换为long,若转换失败,则返回0。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static long ParseToLong(this object obj)
|
|
{
|
|
if (obj == null)
|
|
return 0L;
|
|
|
|
try
|
|
{
|
|
string str = obj.ParseToString();
|
|
if (string.IsNullOrEmpty(str))
|
|
{
|
|
return 0;
|
|
}
|
|
return long.Parse(str);
|
|
}
|
|
catch
|
|
{
|
|
return 0L;
|
|
}
|
|
}
|
|
|
|
public static long? ParseToNullableLong(this object obj)
|
|
{
|
|
if (obj == null)
|
|
return null;
|
|
|
|
try
|
|
{
|
|
string str = obj.ParseToString();
|
|
if (string.IsNullOrEmpty(str))
|
|
{
|
|
return null;
|
|
}
|
|
return long.Parse(str);
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将object转换为long,若转换失败,则返回指定值。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <param name="defaultValue"></param>
|
|
/// <returns></returns>
|
|
public static long ParseToLong(this string str, long defaultValue)
|
|
{
|
|
if (str == null)
|
|
return defaultValue;
|
|
|
|
try
|
|
{
|
|
return long.Parse(str);
|
|
}
|
|
catch
|
|
{
|
|
return defaultValue;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转换为int
|
|
/// <summary>
|
|
/// 将object转换为int,若转换失败,则返回0。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static int ParseToInt(this object str)
|
|
{
|
|
if (str == null)
|
|
return 0;
|
|
|
|
try
|
|
{
|
|
return Convert.ToInt32(str);
|
|
}
|
|
catch
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
public static int? ParseToNullableInt(this object str)
|
|
{
|
|
// 1. 快速判断:如果为 null 或 DBNull,直接返回
|
|
if (str == null || str == DBNull.Value)
|
|
return null;
|
|
|
|
// 2. 尝试直接转换类型(处理 int, short, long 等)
|
|
if (str is int intVal)
|
|
return intVal;
|
|
if (str is long longVal && longVal >= int.MinValue && longVal <= int.MaxValue)
|
|
return (int)longVal;
|
|
|
|
// 3. 针对字符串进行处理(支持空格、空字符串)
|
|
if (str is string strVal)
|
|
{
|
|
// 如果字符串为 null 或空白,视为 null
|
|
if (string.IsNullOrWhiteSpace(strVal))
|
|
return null;
|
|
|
|
if (int.TryParse(strVal, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result))
|
|
return result;
|
|
|
|
return null;
|
|
}
|
|
|
|
// 4. 其他类型(如 bool, DateTime)统一返回 null,保持严格
|
|
try
|
|
{
|
|
return Convert.ToInt32(str);
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public static int DecimalPointParseToInt(this object str)
|
|
{
|
|
try
|
|
{
|
|
string temp = str.ParseToString();
|
|
int i = temp.IndexOf('.');
|
|
if (i > 0)
|
|
{
|
|
temp = temp.Substring(0, i);
|
|
}
|
|
return Convert.ToInt32(temp);
|
|
}
|
|
catch
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将object转换为int,若转换失败,则返回指定值。不抛出异常。
|
|
/// null返回默认值
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <param name="defaultValue"></param>
|
|
/// <returns></returns>
|
|
public static int ParseToInt(this object str, int defaultValue)
|
|
{
|
|
if (str == null)
|
|
{
|
|
return defaultValue;
|
|
}
|
|
try
|
|
{
|
|
return Convert.ToInt32(str);
|
|
}
|
|
catch
|
|
{
|
|
return defaultValue;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转换为short
|
|
/// <summary>
|
|
/// 将object转换为short,若转换失败,则返回0。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static short ParseToShort(this object obj)
|
|
{
|
|
try
|
|
{
|
|
return short.Parse(obj.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将object转换为short,若转换失败,则返回指定值。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static short ParseToShort(this object str, short defaultValue)
|
|
{
|
|
try
|
|
{
|
|
return short.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return defaultValue;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转换为demical
|
|
/// <summary>
|
|
/// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static decimal ParseToDecimal(this object str, decimal defaultValue)
|
|
{
|
|
try
|
|
{
|
|
if (str is DBNull) { return defaultValue; }
|
|
return decimal.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将object转换为demical,若转换失败,则返回0。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static decimal ParseToDecimal(this object str)
|
|
{
|
|
try
|
|
{
|
|
if (str is DBNull) { return 0; }
|
|
return decimal.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
public static decimal? ParseToNullableDecimal(this object str)
|
|
{
|
|
try
|
|
{
|
|
return decimal.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转化为bool
|
|
/// <summary>
|
|
/// 将object转换为bool,若转换失败,则返回false。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static bool ParseToBool(this object str)
|
|
{
|
|
try
|
|
{
|
|
if (str is null)
|
|
return false;
|
|
return bool.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static bool ParseToBool(this object str, bool result)
|
|
{
|
|
try
|
|
{
|
|
return bool.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return result;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转换为float
|
|
/// <summary>
|
|
/// 将object转换为float,若转换失败,则返回0。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static float ParseToFloat(this object str)
|
|
{
|
|
try
|
|
{
|
|
return float.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将object转换为float,若转换失败,则返回指定值。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static float ParseToFloat(this object str, float result)
|
|
{
|
|
try
|
|
{
|
|
return float.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return result;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转换为Guid
|
|
/// <summary>
|
|
/// 将string转换为Guid,若转换失败,则返回Guid.Empty。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static Guid ParseToGuid(this string str)
|
|
{
|
|
try
|
|
{
|
|
return new Guid(str);
|
|
}
|
|
catch
|
|
{
|
|
return Guid.Empty;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转换为DateTime
|
|
|
|
public static DateTime? ParseToDateTimeNullable(this string str)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrWhiteSpace(str))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
return DateTime.Parse(str);
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
|
|
if (str.Contains("年") && str.Contains("月") && str.Contains("日") && !str.Contains("周"))
|
|
str = str.Replace("年", "-").Replace("月", "-").Replace("日", "").Replace("时", ":").Replace("分", ":").Replace("秒", "").Trim(' ', ':');
|
|
if (str.Contains("-") || str.Contains("/"))
|
|
{
|
|
return DateTime.Parse(str);
|
|
}
|
|
else
|
|
{
|
|
int length = str.Length;
|
|
switch (length)
|
|
{
|
|
case 4:
|
|
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 6:
|
|
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 8:
|
|
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 10:
|
|
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 12:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 14:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
|
default:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将string转换为DateTime,若转换失败,则返回日期最小值。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static DateTime ParseToDateTime(this string str)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrWhiteSpace(str))
|
|
{
|
|
return DateTime.MinValue;
|
|
}
|
|
if (str.Contains("-") || str.Contains("/"))
|
|
{
|
|
return DateTime.Parse(str);
|
|
}
|
|
else
|
|
{
|
|
int length = str.Length;
|
|
switch (length)
|
|
{
|
|
case 4:
|
|
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 6:
|
|
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 8:
|
|
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 10:
|
|
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 12:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 14:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
|
default:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return DateTime.MinValue;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将string转换为DateTime,若转换失败,则返回默认值。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <param name="defaultValue"></param>
|
|
/// <returns></returns>
|
|
public static DateTime ParseToDateTime(this string str, DateTime? defaultValue)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrWhiteSpace(str))
|
|
{
|
|
return defaultValue.GetValueOrDefault();
|
|
}
|
|
if (str.Contains("-") || str.Contains("/"))
|
|
{
|
|
return DateTime.Parse(str);
|
|
}
|
|
else
|
|
{
|
|
int length = str.Length;
|
|
switch (length)
|
|
{
|
|
case 4:
|
|
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 6:
|
|
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 8:
|
|
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 10:
|
|
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 12:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 14:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
|
default:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return defaultValue.GetValueOrDefault();
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转换为string
|
|
/// <summary>
|
|
/// 将object转换为string,若转换失败,则返回""。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <returns></returns>
|
|
public static string ParseToString(this object obj)
|
|
{
|
|
try
|
|
{
|
|
if (obj == null)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
else
|
|
{
|
|
if (obj is DateTime)
|
|
return (obj as DateTime?).Value.ToString("yyyy-MM-dd HH:mm:ss");
|
|
return obj.ToString();
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return string.Empty;
|
|
}
|
|
}
|
|
|
|
public static string ParseToNullableString(this object obj)
|
|
{
|
|
try
|
|
{
|
|
if (obj == null)
|
|
{
|
|
return null;
|
|
}
|
|
else
|
|
{
|
|
if (obj is DateTime)
|
|
return (obj as DateTime?).Value.ToString("yyyy-MM-dd HH:mm:ss");
|
|
return obj.ToString();
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static string ParseToStrings<T>(this object obj, string split = ",")
|
|
{
|
|
try
|
|
{
|
|
var list = obj as IEnumerable<T>;
|
|
if (list != null)
|
|
{
|
|
return string.Join(split, list);
|
|
}
|
|
else
|
|
{
|
|
return obj.ToString();
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return string.Empty;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 转换为double
|
|
/// <summary>
|
|
/// 将object转换为double,若转换失败,则返回0。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="obj"></param>
|
|
/// <returns></returns>
|
|
public static double ParseToDouble(this object obj)
|
|
{
|
|
try
|
|
{
|
|
return double.Parse(obj.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将object转换为double,若转换失败,则返回指定值。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="str"></param>
|
|
/// <param name="defaultValue"></param>
|
|
/// <returns></returns>
|
|
public static double ParseToDouble(this object str, double defaultValue)
|
|
{
|
|
try
|
|
{
|
|
return double.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return defaultValue;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 字符串转指定类型Array
|
|
public static T[] SplitToArray<T>(this string value, string split = ",")
|
|
{
|
|
if (string.IsNullOrEmpty(value))
|
|
{
|
|
return default(T[]);
|
|
}
|
|
var arr = value.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
|
|
return arr;
|
|
}
|
|
|
|
public static T[] SplitToArray<T>(this string value, string[] split)
|
|
{
|
|
if (string.IsNullOrEmpty(value))
|
|
{
|
|
return default(T[]);
|
|
}
|
|
var arr = value.Split(split, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
|
|
return arr;
|
|
}
|
|
#endregion
|
|
|
|
#region 字符串转指定类型List
|
|
public static List<T> SplitToList<T>(this string value, string split = ",")
|
|
{
|
|
if (string.IsNullOrEmpty(value))
|
|
{
|
|
return new List<T>();
|
|
}
|
|
var list = value.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToList();
|
|
return list;
|
|
}
|
|
|
|
public static List<T> SplitToList<T>(this string value, string[] split)
|
|
{
|
|
if (string.IsNullOrEmpty(value))
|
|
{
|
|
return new List<T>();
|
|
}
|
|
var list = value.Split(split, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToList();
|
|
return list;
|
|
}
|
|
#endregion
|
|
|
|
#region 强制转换类型
|
|
/// <summary>
|
|
/// 强制转换类型
|
|
/// </summary>
|
|
/// <typeparam name="TResult"></typeparam>
|
|
/// <param name="source"></param>
|
|
/// <returns></returns>
|
|
public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source)
|
|
{
|
|
foreach (object item in source)
|
|
{
|
|
yield return (TResult)Convert.ChangeType(item, typeof(TResult));
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Object转换为Json
|
|
public static string ParseToJson(this object obj)
|
|
{
|
|
return JsonConvert.SerializeObject(obj);
|
|
}
|
|
#endregion
|
|
|
|
#region Json转为Object
|
|
public static T ParseToObject<T>(this string json)
|
|
{
|
|
if (string.IsNullOrEmpty(json))
|
|
{
|
|
return Activator.CreateInstance<T>();
|
|
}
|
|
return JsonConvert.DeserializeObject<T>(json);
|
|
}
|
|
#endregion
|
|
|
|
#region 深拷贝(克隆出一个新对象,拷贝对象里面的数据和子对象)
|
|
public static T DeepClone<T>(this T o)
|
|
{
|
|
return o.ParseToJson().ParseToObject<T>();
|
|
// 这种方式在用 Obfuscator 的时候有问题
|
|
//using (MemoryStream stream = new MemoryStream())
|
|
//{
|
|
// BinaryFormatter formatter = new BinaryFormatter();
|
|
// formatter.Serialize(stream, o);
|
|
// stream.Position = 0;
|
|
// return (T)formatter.Deserialize(stream);
|
|
//}
|
|
}
|
|
#endregion
|
|
|
|
#region 浅拷贝(拷贝对象里面的数据[property and field],但不拷贝对象里面的子对象)
|
|
public static void ShadowClone<T1, T2>(this T1 source, ref T2 destination)
|
|
{
|
|
var sourceMembers = ReflectionHelper.GetMembers(source.GetType());
|
|
var destinationMembers = ReflectionHelper.GetMembers(destination.GetType());
|
|
|
|
// Copy data from source to destination
|
|
foreach (var sourceMember in sourceMembers)
|
|
{
|
|
if (!ReflectionHelper.CanRead(sourceMember))
|
|
{
|
|
continue;
|
|
}
|
|
var destinationMember = destinationMembers.FirstOrDefault(x => x.Name.ToLower() == sourceMember.Name.ToLower());
|
|
if (destinationMember == null || !ReflectionHelper.CanWrite(destinationMember))
|
|
{
|
|
continue;
|
|
}
|
|
ReflectionHelper.SetObjectValue(ref destination, destinationMember, ReflectionHelper.GetMemberValue(source, sourceMember));
|
|
}
|
|
}
|
|
#endregion
|
|
}
|
|
}
|