ObjectExtension.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using Newtonsoft.Json;
  7. using System.Text.Json;
  8. namespace Admin.NET.Core;
  9. /// <summary>
  10. /// 对象拓展
  11. /// </summary>
  12. [SuppressSniffer]
  13. public static partial class ObjectExtension
  14. {
  15. /// <summary>
  16. /// 判断类型是否实现某个泛型
  17. /// </summary>
  18. /// <param name="type">类型</param>
  19. /// <param name="generic">泛型类型</param>
  20. /// <returns>bool</returns>
  21. public static bool HasImplementedRawGeneric(this Type type, Type generic)
  22. {
  23. // 检查接口类型
  24. var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
  25. if (isTheRawGenericType) return true;
  26. // 检查类型
  27. while (type != null && type != typeof(object))
  28. {
  29. isTheRawGenericType = IsTheRawGenericType(type);
  30. if (isTheRawGenericType) return true;
  31. type = type.BaseType;
  32. }
  33. return false;
  34. // 判断逻辑
  35. bool IsTheRawGenericType(Type type) => generic == (type.IsGenericType ? type.GetGenericTypeDefinition() : type);
  36. }
  37. /// <summary>
  38. /// 将字典转化为QueryString格式
  39. /// </summary>
  40. /// <param name="dict"></param>
  41. /// <param name="urlEncode"></param>
  42. /// <returns></returns>
  43. public static string ToQueryString(this Dictionary<string, string> dict, bool urlEncode = true)
  44. {
  45. return string.Join("&", dict.Select(p => $"{(urlEncode ? p.Key?.UrlEncode() : "")}={(urlEncode ? p.Value?.UrlEncode() : "")}"));
  46. }
  47. /// <summary>
  48. /// 将字符串URL编码
  49. /// </summary>
  50. /// <param name="str"></param>
  51. /// <returns></returns>
  52. public static string UrlEncode(this string str)
  53. {
  54. return string.IsNullOrEmpty(str) ? "" : System.Uri.EscapeDataString(str);
  55. }
  56. /// <summary>
  57. /// 对象序列化成Json字符串
  58. /// </summary>
  59. /// <param name="obj"></param>
  60. /// <returns></returns>
  61. public static string ToJson(this object obj)
  62. {
  63. var jsonSettings = SetNewtonsoftJsonSetting();
  64. return JSON.GetJsonSerializer().Serialize(obj,jsonSettings);
  65. }
  66. private static JsonSerializerSettings SetNewtonsoftJsonSetting()
  67. {
  68. JsonSerializerSettings setting = new JsonSerializerSettings();
  69. setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
  70. setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
  71. setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
  72. setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
  73. //setting.ContractResolver = new HelErpContractResolver("StartTime", customName);
  74. return setting;
  75. }
  76. /// <summary>
  77. /// Json字符串反序列化成对象
  78. /// </summary>
  79. /// <typeparam name="T"></typeparam>
  80. /// <param name="json"></param>
  81. /// <returns></returns>
  82. public static T ToObject<T>(this string json)
  83. {
  84. return JSON.GetJsonSerializer().Deserialize<T>(json);
  85. }
  86. /// <summary>
  87. /// 将object转换为long,若失败则返回0
  88. /// </summary>
  89. /// <param name="obj"></param>
  90. /// <returns></returns>
  91. public static long ParseToLong(this object obj)
  92. {
  93. try
  94. {
  95. return long.Parse(obj.ToString());
  96. }
  97. catch
  98. {
  99. return 0L;
  100. }
  101. }
  102. /// <summary>
  103. /// 将object转换为long,若失败则返回指定值
  104. /// </summary>
  105. /// <param name="str"></param>
  106. /// <param name="defaultValue"></param>
  107. /// <returns></returns>
  108. public static long ParseToLong(this string str, long defaultValue)
  109. {
  110. try
  111. {
  112. return long.Parse(str);
  113. }
  114. catch
  115. {
  116. return defaultValue;
  117. }
  118. }
  119. /// <summary>
  120. /// 将object转换为double,若失败则返回0
  121. /// </summary>
  122. /// <param name="obj"></param>
  123. /// <returns></returns>
  124. public static double ParseToDouble(this object obj)
  125. {
  126. try
  127. {
  128. return double.Parse(obj.ToString());
  129. }
  130. catch
  131. {
  132. return 0;
  133. }
  134. }
  135. /// <summary>
  136. /// 将object转换为double,若失败则返回指定值
  137. /// </summary>
  138. /// <param name="str"></param>
  139. /// <param name="defaultValue"></param>
  140. /// <returns></returns>
  141. public static double ParseToDouble(this object str, double defaultValue)
  142. {
  143. try
  144. {
  145. return double.Parse(str.ToString());
  146. }
  147. catch
  148. {
  149. return defaultValue;
  150. }
  151. }
  152. /// <summary>
  153. /// 将string转换为DateTime,若失败则返回日期最小值
  154. /// </summary>
  155. /// <param name="str"></param>
  156. /// <returns></returns>
  157. public static DateTime ParseToDateTime(this string str)
  158. {
  159. try
  160. {
  161. if (string.IsNullOrWhiteSpace(str))
  162. {
  163. return DateTime.MinValue;
  164. }
  165. if (str.Contains('-') || str.Contains('/'))
  166. {
  167. return DateTime.Parse(str);
  168. }
  169. else
  170. {
  171. int length = str.Length;
  172. switch (length)
  173. {
  174. case 4:
  175. return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
  176. case 6:
  177. return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
  178. case 8:
  179. return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
  180. case 10:
  181. return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
  182. case 12:
  183. return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
  184. case 14:
  185. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  186. default:
  187. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  188. }
  189. }
  190. }
  191. catch
  192. {
  193. return DateTime.MinValue;
  194. }
  195. }
  196. /// <summary>
  197. /// 将string转换为DateTime,若失败则返回默认值
  198. /// </summary>
  199. /// <param name="str"></param>
  200. /// <param name="defaultValue"></param>
  201. /// <returns></returns>
  202. public static DateTime ParseToDateTime(this string str, DateTime? defaultValue)
  203. {
  204. try
  205. {
  206. if (string.IsNullOrWhiteSpace(str))
  207. {
  208. return defaultValue.GetValueOrDefault();
  209. }
  210. if (str.Contains('-') || str.Contains('/'))
  211. {
  212. return DateTime.Parse(str);
  213. }
  214. else
  215. {
  216. int length = str.Length;
  217. switch (length)
  218. {
  219. case 4:
  220. return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
  221. case 6:
  222. return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
  223. case 8:
  224. return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
  225. case 10:
  226. return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
  227. case 12:
  228. return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
  229. case 14:
  230. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  231. default:
  232. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  233. }
  234. }
  235. }
  236. catch
  237. {
  238. return defaultValue.GetValueOrDefault();
  239. }
  240. }
  241. /// <summary>
  242. /// 将 string 时间日期格式转换成字符串 如 {yyyy} => 2024
  243. /// </summary>
  244. /// <param name="str"></param>
  245. /// <returns></returns>
  246. public static string ParseToDateTimeForRep(this string str)
  247. {
  248. if (string.IsNullOrWhiteSpace(str))
  249. str = $"{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}";
  250. var date = DateTime.Now;
  251. var reg = new Regex(@"(\{.+?})");
  252. var match = reg.Matches(str);
  253. match.ToList().ForEach(u =>
  254. {
  255. var temp = date.ToString(u.ToString().Substring(1, u.Length - 2));
  256. str = str.Replace(u.ToString(), temp);
  257. });
  258. return str;
  259. }
  260. /// <summary>
  261. /// 是否有值
  262. /// </summary>
  263. /// <param name="obj"></param>
  264. /// <returns></returns>
  265. public static bool IsNullOrEmpty(this object obj)
  266. {
  267. return obj == null || string.IsNullOrEmpty(obj.ToString());
  268. }
  269. /// <summary>
  270. /// 字符串掩码
  271. /// </summary>
  272. /// <param name="str">字符串</param>
  273. /// <param name="mask">掩码符</param>
  274. /// <returns></returns>
  275. public static string Mask(this string str, char mask = '*')
  276. {
  277. if (string.IsNullOrWhiteSpace(str?.Trim()))
  278. return str;
  279. str = str.Trim();
  280. var masks = mask.ToString().PadLeft(4, mask);
  281. return str.Length switch
  282. {
  283. >= 11 => Regex.Replace(str, "(.{3}).*(.{4})", $"$1{masks}$2"),
  284. 10 => Regex.Replace(str, "(.{3}).*(.{3})", $"$1{masks}$2"),
  285. 9 => Regex.Replace(str, "(.{2}).*(.{3})", $"$1{masks}$2"),
  286. 8 => Regex.Replace(str, "(.{2}).*(.{2})", $"$1{masks}$2"),
  287. 7 => Regex.Replace(str, "(.{1}).*(.{2})", $"$1{masks}$2"),
  288. 6 => Regex.Replace(str, "(.{1}).*(.{1})", $"$1{masks}$2"),
  289. _ => Regex.Replace(str, "(.{1}).*", $"$1{masks}")
  290. };
  291. }
  292. /// <summary>
  293. /// 身份证号掩码
  294. /// </summary>
  295. /// <param name="idCard">身份证号</param>
  296. /// <param name="mask">掩码符</param>
  297. /// <returns></returns>
  298. public static string MaskIdCard(this string idCard, char mask = '*')
  299. {
  300. if (!idCard.TryValidate(ValidationTypes.IDCard).IsValid) return idCard;
  301. var masks = mask.ToString().PadLeft(8, mask);
  302. return Regex.Replace(idCard, @"^(.{6})(.*)(.{4})$", $"$1{masks}$3");
  303. }
  304. /// <summary>
  305. /// 邮箱掩码
  306. /// </summary>
  307. /// <param name="email">邮箱</param>
  308. /// <param name="mask">掩码符</param>
  309. /// <returns></returns>
  310. public static string MaskEmail(this string email, char mask = '*')
  311. {
  312. if (!email.TryValidate(ValidationTypes.EmailAddress).IsValid) return email;
  313. var pos = email.IndexOf("@");
  314. return Mask(email[..pos], mask) + email[pos..];
  315. }
  316. /// <summary>
  317. /// 将字符串转为值类型,若没有得到或者错误返回为空
  318. /// </summary>
  319. /// <typeparam name="T">指定值类型</typeparam>
  320. /// <param name="str">传入字符串</param>
  321. /// <returns>可空值</returns>
  322. public static T? ParseTo<T>(this string str) where T : struct
  323. {
  324. try
  325. {
  326. if (!string.IsNullOrWhiteSpace(str))
  327. {
  328. MethodInfo method = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });
  329. if (method != null)
  330. {
  331. T result = (T)method.Invoke(null, new string[] { str });
  332. return result;
  333. }
  334. }
  335. }
  336. catch
  337. {
  338. }
  339. return null;
  340. }
  341. /// <summary>
  342. /// 将字符串转为值类型,若没有得到或者错误返回为空
  343. /// </summary>
  344. /// <param name="str">传入字符串</param>
  345. /// <param name="type">目标类型</param>
  346. /// <returns>可空值</returns>
  347. public static object ParseTo(this string str, Type type)
  348. {
  349. try
  350. {
  351. if (type.Name == "String")
  352. return str;
  353. if (!string.IsNullOrWhiteSpace(str))
  354. {
  355. var _type = type;
  356. if (type.Name.StartsWith("Nullable"))
  357. _type = type.GetGenericArguments()[0];
  358. MethodInfo method = _type.GetMethod("Parse", new Type[] { typeof(string) });
  359. if (method != null)
  360. return method.Invoke(null, new string[] { str });
  361. }
  362. }
  363. catch
  364. {
  365. }
  366. return null;
  367. }
  368. /// <summary>
  369. /// 将一个对象属性值赋给另一个指定对象属性, 只复制相同属性的
  370. /// </summary>
  371. /// <param name="src">原数据对象</param>
  372. /// <param name="target">目标数据对象</param>
  373. /// <param name="changeProperties">属性集,键为原属性,值为目标属性</param>
  374. /// <param name="unChangeProperties">属性集,目标不修改的属性</param>
  375. public static void CopyTo(object src, object target, Dictionary<string, string> changeProperties = null, string[] unChangeProperties = null)
  376. {
  377. if (src == null || target == null)
  378. throw new ArgumentException("src == null || target == null ");
  379. var SourceType = src.GetType();
  380. var TargetType = target.GetType();
  381. if (changeProperties == null || changeProperties.Count == 0)
  382. {
  383. var fields = TargetType.GetProperties();
  384. changeProperties = fields.Select(m => m.Name).ToDictionary(m => m);
  385. }
  386. if (unChangeProperties == null || unChangeProperties.Length == 0)
  387. {
  388. foreach (var item in changeProperties)
  389. {
  390. var srcProperty = SourceType.GetProperty(item.Key);
  391. if (srcProperty != null)
  392. {
  393. var sourceVal = srcProperty.GetValue(src, null);
  394. var tarProperty = TargetType.GetProperty(item.Value);
  395. tarProperty?.SetValue(target, sourceVal, null);
  396. }
  397. }
  398. }
  399. else
  400. {
  401. foreach (var item in changeProperties)
  402. {
  403. if (!unChangeProperties.Any(m => m == item.Value))
  404. {
  405. var srcProperty = SourceType.GetProperty(item.Key);
  406. if (srcProperty != null)
  407. {
  408. var sourceVal = srcProperty.GetValue(src, null);
  409. var tarProperty = TargetType.GetProperty(item.Value);
  410. tarProperty?.SetValue(target, sourceVal, null);
  411. }
  412. }
  413. }
  414. }
  415. }
  416. /// <summary>
  417. /// 深复制
  418. /// </summary>
  419. /// <typeparam name="T">深复制源对象</typeparam>
  420. /// <param name="obj">对象</param>
  421. /// <returns></returns>
  422. public static T DeepCopy<T>(this T obj)
  423. {
  424. var jsonSettings = SetNewtonsoftJsonSetting();
  425. var json = JSON.Serialize(obj, jsonSettings);
  426. return JSON.Deserialize<T>(json);
  427. }
  428. }