ObjectExtension.cs 15 KB

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