ObjectExtension.cs 16 KB

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