using System.Collections;
using System.Text.RegularExpressions;
namespace SafeCampus.Core.Extension
{
public static partial class Extensions
{
#region 转换为long
///
/// 将object转换为long,若转换失败,则返回0。不抛出异常。
///
///
///
public static long ParseToLong(this object obj)
{
try
{
if (obj == null)
return 0L;
return long.Parse(obj.ToString());
}
catch
{
return 0L;
}
}
///
/// 将object转换为long,若转换失败,则返回指定值。不抛出异常。
///
///
///
///
public static long ParseToLong(this string str, long defaultValue)
{
try
{
return long.Parse(str);
}
catch
{
return defaultValue;
}
}
#endregion
#region 转换为int
///
/// 将object转换为int,若转换失败,则返回0。不抛出异常。
///
///
///
public static int ParseToInt(this object str)
{
try
{
return Convert.ToInt32(str);
}
catch
{
return 0;
}
}
///
/// 将object转换为int,若转换失败,则返回指定值。不抛出异常。
/// null返回默认值
///
///
///
///
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
///
/// 将object转换为short,若转换失败,则返回0。不抛出异常。
///
///
///
public static short ParseToShort(this object obj)
{
try
{
return short.Parse(obj.ToString());
}
catch
{
return 0;
}
}
///
/// 将object转换为short,若转换失败,则返回指定值。不抛出异常。
///
///
///
///
public static short ParseToShort(this object str, short defaultValue)
{
try
{
return short.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
#endregion
#region 转换为demical
///
/// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。
///
///
///
///
public static decimal ParseToDecimal(this object str, decimal defaultValue)
{
try
{
return decimal.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
///
/// 将object转换为demical,若转换失败,则返回0。不抛出异常。
///
///
///
public static decimal ParseToDecimal(this object str)
{
try
{
return decimal.Parse(str.ToString());
}
catch
{
return 0;
}
}
#endregion
#region 转化为bool
///
/// 将object转换为bool,若转换失败,则返回false。不抛出异常。
///
///
///
public static bool ParseToBool(this object str)
{
try
{
return bool.Parse(str.ToString());
}
catch
{
return false;
}
}
///
/// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。
///
///
///
///
public static bool ParseToBool(this object str, bool result)
{
try
{
return bool.Parse(str.ToString());
}
catch
{
return result;
}
}
#endregion
#region 转换为float
///
/// 将object转换为float,若转换失败,则返回0。不抛出异常。
///
///
///
public static float ParseToFloat(this object str)
{
try
{
return float.Parse(str.ToString());
}
catch
{
return 0;
}
}
///
/// 将object转换为float,若转换失败,则返回指定值。不抛出异常。
///
///
///
///
public static float ParseToFloat(this object str, float result)
{
try
{
return float.Parse(str.ToString());
}
catch
{
return result;
}
}
#endregion
#region 转换为Guid
///
/// 将string转换为Guid,若转换失败,则返回Guid.Empty。不抛出异常。
///
///
///
public static Guid ParseToGuid(this string str)
{
try
{
return new Guid(str);
}
catch
{
return Guid.Empty;
}
}
#endregion
#region 转换为DateTime
///
/// 将string转换为DateTime,若转换失败,则返回日期最小值。不抛出异常。
///
///
///
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;
}
}
///
/// 将string转换为DateTime,若转换失败,则返回默认值。
///
///
///
///
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
///
/// 将object转换为string,若转换失败,则返回""。不抛出异常。
///
///
///
public static string ParseToString(this object obj)
{
try
{
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
catch
{
return string.Empty;
}
}
public static string ParseToStrings(this object obj)
{
try
{
if (obj is IEnumerable list)
{
return string.Join(",", list);
}
else
{
return obj.ToString();
}
}
catch
{
return string.Empty;
}
}
#endregion
#region 转换为double
///
/// 将object转换为double,若转换失败,则返回0。不抛出异常。
///
///
///
public static double ParseToDouble(this object obj)
{
try
{
return double.Parse(obj.ToString());
}
catch
{
return 0;
}
}
///
/// 将object转换为double,若转换失败,则返回指定值。不抛出异常。
///
///
///
///
public static double ParseToDouble(this object str, double defaultValue)
{
try
{
return double.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
#endregion
#region 强制转换类型
///
/// 强制转换类型
///
///
///
///
public static IEnumerable CastSuper(this IEnumerable source)
{
foreach (object item in source)
{
yield return (TResult)Convert.ChangeType(item, typeof(TResult));
}
}
#endregion
#region 阿拉伯数字转换为中文数字(0-99999)
public static string NumberToChinese(int num)
{
string strNum = num.ToString();
string result = "";
if (strNum.Length == 5)
{//万
result += OneBitNumberToChinese(strNum.Substring(0, 1)) + "万";
strNum = strNum.Substring(1);
}
if (strNum.Length == 4)
{//千
string secondBitNumber = strNum.Substring(0, 1);
if (secondBitNumber == "0") result += "零";
else result += OneBitNumberToChinese(secondBitNumber) + "千";
strNum = strNum.Substring(1);
}
if (strNum.Length == 3)
{//百
string hundredBitNumber = strNum.Substring(0, 1);
if (hundredBitNumber == "0" && result.Substring(result.Length - 1) != "零") result += "零";
else result += OneBitNumberToChinese(hundredBitNumber) + "百";
strNum = strNum.Substring(1);
}
if (strNum.Length == 2)
{//十
string hundredBitNumber = strNum.Substring(0, 1);
if (hundredBitNumber == "0" && result.Substring(result.Length - 1) != "零") result += "零";
else if (hundredBitNumber == "1" && string.IsNullOrEmpty(result)) result += "十";//10->十
else result += OneBitNumberToChinese(hundredBitNumber) + "十";
strNum = strNum.Substring(1);
}
if (strNum.Length == 1)
{//个
if (strNum == "0") result += "零";
else result += OneBitNumberToChinese(strNum);
}
//100->一百零零
if (!string.IsNullOrEmpty(result) && result != "零") result = result.TrimEnd('零');
return result;
}
//数字1-9转换为中文数字
private static string OneBitNumberToChinese(string num)
{
string numStr = "123456789";
string chineseStr = "一二三四五六七八九";
string result = "";
int numIndex = numStr.IndexOf(num);
if (numIndex > -1)
{
result = chineseStr.Substring(numIndex, 1);
}
return result;
}
#endregion
#region 日期转大写
///
/// 年月日转换为大写
///
///
///
public static string YMDToUpper(DateTime date)
{
int year = date.Year;
int month = date.Month;
int day = date.Day;
return numtoUpper(year) + "年" + monthtoUpper(month) + "月" + daytoUpper(day) + "日";
}
///
/// 年月转换为大写
///
///
///
public static string YMToUpper(DateTime date)
{
int year = date.Year;
int month = date.Month;
return numtoUpper(year) + "年" + monthtoUpper(month) + "月";
}
//把数字转换为大写
private static string numtoUpper(int num)
{
String str = num.ToString();
string rstr = "";
int n;
for (int i = 0; i < str.Length; i++)
{
n = Convert.ToInt16(str[i].ToString());//char转数字,转换为字符串,再转数字
switch (n)
{
case 0:
rstr = rstr + "〇";
break;
case 1:
rstr = rstr + "一";
break;
case 2:
rstr = rstr + "二";
break;
case 3:
rstr = rstr + "三";
break;
case 4:
rstr = rstr + "四";
break;
case 5:
rstr = rstr + "五";
break;
case 6:
rstr = rstr + "六";
break;
case 7:
rstr = rstr + "七";
break;
case 8:
rstr = rstr + "八";
break;
default:
rstr = rstr + "九";
break;
}
}
return rstr;
}
//月转化为大写
private static string monthtoUpper(int month)
{
if (month < 10)
{
return numtoUpper(month);
}
else if (month == 10)
{
return "十";
}
else
{
return "十" + numtoUpper(month - 10);
}
}
//日转化为大写
private static string daytoUpper(int day)
{
if (day < 20)
{
return monthtoUpper(day);
}
else
{
String str = day.ToString();
if (str[1] == '0')
{
return numtoUpper(Convert.ToInt16(str[0].ToString())) + "十";
}
else
{
return numtoUpper(Convert.ToInt16(str[0].ToString())) + "十" + numtoUpper(Convert.ToInt16(str[1].ToString()));
}
}
}
#endregion
#region 时间戳转日期
///
/// 时间戳转日期
///
///
///
///
public static DateTime StampToDatetime(this long timeStamp, bool isMinSeconds = false)
{
var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));//当地时区
//返回转换后的日期
if (isMinSeconds)
return startTime.AddMilliseconds(timeStamp);
else
return startTime.AddSeconds(timeStamp);
}
///
/// 时间戳转日期
///
///
///
///
public static DateTime StampToDatetime(this string timeStamp, bool isMinSeconds = false)
{
var timeStampLong = long.Parse(timeStamp);
var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));//当地时区
//返回转换后的日期
if (isMinSeconds)
return startTime.AddMilliseconds(timeStampLong);
else
return startTime.AddSeconds(timeStampLong);
}
#endregion
#region 字符串正则替换
///
/// 字符串正则替换
///
///
///
///
///
///
public static string ReplaceMatchStr(this string targetStr, string patternStr, string replaceStr,bool isRecursion = true)
{
Regex regex= new Regex(patternStr);
Match match= regex.Match(targetStr);
return ReplaceMatchingStr(targetStr,match,replaceStr,isRecursion);
}
private static string ReplaceMatchingStr(string targetStr, Match match, string replaceStr, bool isRecursion)
{
//是否匹配成功
if (match.Success)
{
//处理字符串
targetStr = ReplaceStr(targetStr, match, replaceStr);
//是否递归匹配
if (isRecursion)
targetStr = ReplaceMatchingStr(targetStr, match.NextMatch(), replaceStr, true);
}
return targetStr;
}
private static string ReplaceStr(string targetStr, Match match, string replaceStr)
{
//替换字符
string newStr = targetStr.Replace(match.ToString(), replaceStr);
return newStr;
}
public static string RedactString(this string input, int start, int length, char replaceChar)
{
if (input.Length < start + length)
{
return input;
}
string prefix = input.Substring(0, start);
string suffix = input.Substring(start + length);
string replacement = new string(replaceChar, length);
return prefix + replacement + suffix;
}
#endregion
}
}