ObjectExtension.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. namespace Admin.NET.Core;
  10. /// <summary>
  11. /// 对象拓展
  12. /// </summary>
  13. [SuppressSniffer]
  14. public static partial class ObjectExtension
  15. {
  16. /// <summary>
  17. /// 判断类型是否实现某个泛型
  18. /// </summary>
  19. /// <param name="type">类型</param>
  20. /// <param name="generic">泛型类型</param>
  21. /// <returns>bool</returns>
  22. public static bool HasImplementedRawGeneric(this Type type, Type generic)
  23. {
  24. // 检查接口类型
  25. var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
  26. if (isTheRawGenericType) return true;
  27. // 检查类型
  28. while (type != null && type != typeof(object))
  29. {
  30. isTheRawGenericType = IsTheRawGenericType(type);
  31. if (isTheRawGenericType) return true;
  32. type = type.BaseType;
  33. }
  34. return false;
  35. // 判断逻辑
  36. bool IsTheRawGenericType(Type type) => generic == (type.IsGenericType ? type.GetGenericTypeDefinition() : type);
  37. }
  38. /// <summary>
  39. /// 将字典转化为QueryString格式
  40. /// </summary>
  41. /// <param name="dict"></param>
  42. /// <param name="urlEncode"></param>
  43. /// <returns></returns>
  44. public static string ToQueryString(this Dictionary<string, string> dict, bool urlEncode = true)
  45. {
  46. return string.Join("&", dict.Select(p => $"{(urlEncode ? p.Key?.UrlEncode() : "")}={(urlEncode ? p.Value?.UrlEncode() : "")}"));
  47. }
  48. /// <summary>
  49. /// 将字符串URL编码
  50. /// </summary>
  51. /// <param name="str"></param>
  52. /// <returns></returns>
  53. public static string UrlEncode(this string str)
  54. {
  55. return string.IsNullOrEmpty(str) ? "" : System.Web.HttpUtility.UrlEncode(str, Encoding.UTF8);
  56. }
  57. /// <summary>
  58. /// 对象序列化成Json字符串
  59. /// </summary>
  60. /// <param name="obj"></param>
  61. /// <returns></returns>
  62. public static string ToJson(this object obj)
  63. {
  64. return JSON.GetJsonSerializer().Serialize(obj);
  65. }
  66. /// <summary>
  67. /// Json字符串反序列化成对象
  68. /// </summary>
  69. /// <typeparam name="T"></typeparam>
  70. /// <param name="json"></param>
  71. /// <returns></returns>
  72. public static T ToObject<T>(this string json)
  73. {
  74. return JSON.GetJsonSerializer().Deserialize<T>(json);
  75. }
  76. /// <summary>
  77. /// 将object转换为long,若失败则返回0
  78. /// </summary>
  79. /// <param name="obj"></param>
  80. /// <returns></returns>
  81. public static long ParseToLong(this object obj)
  82. {
  83. try
  84. {
  85. return long.Parse(obj.ToString());
  86. }
  87. catch
  88. {
  89. return 0L;
  90. }
  91. }
  92. /// <summary>
  93. /// 将object转换为long,若失败则返回指定值
  94. /// </summary>
  95. /// <param name="str"></param>
  96. /// <param name="defaultValue"></param>
  97. /// <returns></returns>
  98. public static long ParseToLong(this string str, long defaultValue)
  99. {
  100. try
  101. {
  102. return long.Parse(str);
  103. }
  104. catch
  105. {
  106. return defaultValue;
  107. }
  108. }
  109. /// <summary>
  110. /// 将object转换为double,若失败则返回0
  111. /// </summary>
  112. /// <param name="obj"></param>
  113. /// <returns></returns>
  114. public static double ParseToDouble(this object obj)
  115. {
  116. try
  117. {
  118. return double.Parse(obj.ToString());
  119. }
  120. catch
  121. {
  122. return 0;
  123. }
  124. }
  125. /// <summary>
  126. /// 将object转换为double,若失败则返回指定值
  127. /// </summary>
  128. /// <param name="str"></param>
  129. /// <param name="defaultValue"></param>
  130. /// <returns></returns>
  131. public static double ParseToDouble(this object str, double defaultValue)
  132. {
  133. try
  134. {
  135. return double.Parse(str.ToString());
  136. }
  137. catch
  138. {
  139. return defaultValue;
  140. }
  141. }
  142. /// <summary>
  143. /// 将string转换为DateTime,若失败则返回日期最小值
  144. /// </summary>
  145. /// <param name="str"></param>
  146. /// <returns></returns>
  147. public static DateTime ParseToDateTime(this string str)
  148. {
  149. try
  150. {
  151. if (string.IsNullOrWhiteSpace(str))
  152. {
  153. return DateTime.MinValue;
  154. }
  155. if (str.Contains('-') || str.Contains('/'))
  156. {
  157. return DateTime.Parse(str);
  158. }
  159. else
  160. {
  161. int length = str.Length;
  162. switch (length)
  163. {
  164. case 4:
  165. return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
  166. case 6:
  167. return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
  168. case 8:
  169. return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
  170. case 10:
  171. return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
  172. case 12:
  173. return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
  174. case 14:
  175. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  176. default:
  177. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  178. }
  179. }
  180. }
  181. catch
  182. {
  183. return DateTime.MinValue;
  184. }
  185. }
  186. /// <summary>
  187. /// 将string转换为DateTime,若失败则返回默认值
  188. /// </summary>
  189. /// <param name="str"></param>
  190. /// <param name="defaultValue"></param>
  191. /// <returns></returns>
  192. public static DateTime ParseToDateTime(this string str, DateTime? defaultValue)
  193. {
  194. try
  195. {
  196. if (string.IsNullOrWhiteSpace(str))
  197. {
  198. return defaultValue.GetValueOrDefault();
  199. }
  200. if (str.Contains('-') || str.Contains('/'))
  201. {
  202. return DateTime.Parse(str);
  203. }
  204. else
  205. {
  206. int length = str.Length;
  207. switch (length)
  208. {
  209. case 4:
  210. return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
  211. case 6:
  212. return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
  213. case 8:
  214. return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
  215. case 10:
  216. return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
  217. case 12:
  218. return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
  219. case 14:
  220. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  221. default:
  222. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  223. }
  224. }
  225. }
  226. catch
  227. {
  228. return defaultValue.GetValueOrDefault();
  229. }
  230. }
  231. /// <summary>
  232. /// 判断是否有值
  233. /// </summary>
  234. /// <param name="obj"></param>
  235. /// <returns></returns>
  236. public static bool IsNullOrEmpty(this object obj)
  237. {
  238. return obj == null || string.IsNullOrEmpty(obj.ToString());
  239. }
  240. /// <summary>
  241. /// 字符串掩码
  242. /// </summary>
  243. /// <param name="str">字符串</param>
  244. /// <param name="mask">掩码符</param>
  245. /// <returns></returns>
  246. public static string Mask(this string str, char mask = '*')
  247. {
  248. if (string.IsNullOrWhiteSpace(str?.Trim()))
  249. return str;
  250. str = str.Trim();
  251. var masks = mask.ToString().PadLeft(4, mask);
  252. return str.Length switch
  253. {
  254. >= 11 => Regex.Replace(str, "(.{3}).*(.{4})", $"$1{masks}$2"),
  255. 10 => Regex.Replace(str, "(.{3}).*(.{3})", $"$1{masks}$2"),
  256. 9 => Regex.Replace(str, "(.{2}).*(.{3})", $"$1{masks}$2"),
  257. 8 => Regex.Replace(str, "(.{2}).*(.{2})", $"$1{masks}$2"),
  258. 7 => Regex.Replace(str, "(.{1}).*(.{2})", $"$1{masks}$2"),
  259. 6 => Regex.Replace(str, "(.{1}).*(.{1})", $"$1{masks}$2"),
  260. _ => Regex.Replace(str, "(.{1}).*", $"$1{masks}")
  261. };
  262. }
  263. /// <summary>
  264. /// 身份证号掩码
  265. /// </summary>
  266. /// <param name="idCard">身份证号</param>
  267. /// <param name="mask">掩码符</param>
  268. /// <returns></returns>
  269. public static string MaskIdCard(this string idCard, char mask = '*')
  270. {
  271. if (!idCard.TryValidate(ValidationTypes.IDCard).IsValid) return idCard;
  272. return idCard.Replace("(?<=\\w{3})\\w(?=\\w{4})", $"{mask}");
  273. }
  274. /// <summary>
  275. /// 邮箱掩码
  276. /// </summary>
  277. /// <param name="email">邮箱</param>
  278. /// <param name="mask">掩码符</param>
  279. /// <returns></returns>
  280. public static string MaskEmail(this string email, char mask = '*')
  281. {
  282. if (!email.TryValidate(ValidationTypes.EmailAddress).IsValid) return email;
  283. var masks = mask.ToString().PadLeft(4, mask);
  284. return email.Replace("(^\\w)[^@]*(@.*$)", $"$1{masks}$2");
  285. }
  286. /// <summary>
  287. /// 银行卡号掩码
  288. /// </summary>
  289. /// <param name="bankCard">银行卡号</param>
  290. /// <param name="mask">掩码符</param>
  291. /// <returns></returns>
  292. public static string MaskBankCard(this string bankCard, char mask = '*')
  293. {
  294. if (bankCard.Length < 10) return bankCard;
  295. var masks = mask.ToString().PadLeft(4, mask);
  296. return bankCard.Replace("(\\d{6})\\d{9}(\\d{4})", $"$1{masks}$2");
  297. }
  298. /// <summary>
  299. /// 将字符串转为值类型,如果没有得到或者错误返回为空
  300. /// </summary>
  301. /// <typeparam name="T">指定值类型</typeparam>
  302. /// <param name="str">传入字符串</param>
  303. /// <returns>可空值</returns>
  304. public static Nullable<T> ParseTo<T>(this string str) where T : struct
  305. {
  306. try
  307. {
  308. if (!string.IsNullOrWhiteSpace(str))
  309. {
  310. MethodInfo method = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });
  311. if (method != null)
  312. {
  313. T result = (T)method.Invoke(null, new string[] { str });
  314. return result;
  315. }
  316. }
  317. }
  318. catch
  319. {
  320. }
  321. return null;
  322. }
  323. /// <summary>
  324. /// 将字符串转为值类型,如果没有得到或者错误返回为空
  325. /// </summary>
  326. /// <typeparam name="T">指定值类型</typeparam>
  327. /// <param name="str">传入字符串</param>
  328. /// <param name="type">目标类型</param>
  329. /// <returns>可空值</returns>
  330. public static object ParseTo(this string str, Type type)
  331. {
  332. try
  333. {
  334. if (type.Name == "String")
  335. {
  336. return str;
  337. }
  338. if (!string.IsNullOrWhiteSpace(str))
  339. {
  340. var _type = type;
  341. if (type.Name.StartsWith("Nullable"))
  342. {
  343. _type = type.GetGenericArguments()[0];
  344. }
  345. MethodInfo method = _type.GetMethod("Parse", new Type[] { typeof(string) });
  346. if (method != null)
  347. {
  348. return method.Invoke(null, new string[] { str });
  349. }
  350. }
  351. }
  352. catch
  353. {
  354. }
  355. return null;
  356. }
  357. /// <summary>
  358. /// 将一个的对象属性值赋给另一个制定的对象属性, 只复制相同属性的
  359. /// </summary>
  360. /// <param name="src">原数据对象</param>
  361. /// <param name="target">目标数据对象</param>
  362. /// <param name="changeProperties">属性集,键为原属性,值为目标属性</param>
  363. /// <param name="unChangeProperties">属性集,目标不修改的属性</param>
  364. public static void CopyTo(object src, object target, Dictionary<string, string> changeProperties = null, string[] unChangeProperties = null)
  365. {
  366. if (src == null || target == null)
  367. throw new ArgumentException("src == null || target == null ");
  368. var SourceType = src.GetType();
  369. var TargetType = target.GetType();
  370. if (changeProperties == null || changeProperties.Count == 0)
  371. {
  372. var fields = TargetType.GetProperties();
  373. changeProperties = fields.Select(m => m.Name).ToDictionary(m => m);
  374. }
  375. if (unChangeProperties == null || unChangeProperties.Length == 0)
  376. {
  377. foreach (var item in changeProperties)
  378. {
  379. var srcProperty = SourceType.GetProperty(item.Key);
  380. if (srcProperty != null)
  381. {
  382. var sourceVal = srcProperty
  383. .GetValue(src, null);
  384. var tarProperty = TargetType.GetProperty(item.Value);
  385. if (tarProperty != null)
  386. {
  387. tarProperty.SetValue(target, sourceVal, null);
  388. }
  389. }
  390. }
  391. }
  392. else
  393. {
  394. foreach (var item in changeProperties)
  395. {
  396. if (!unChangeProperties.Any(m => m == item.Value))
  397. {
  398. var srcProperty = SourceType.GetProperty(item.Key);
  399. if (srcProperty != null)
  400. {
  401. var sourceVal = srcProperty
  402. .GetValue(src, null);
  403. var tarProperty = TargetType.GetProperty(item.Value);
  404. if (tarProperty != null)
  405. {
  406. tarProperty.SetValue(target, sourceVal, null);
  407. }
  408. }
  409. }
  410. }
  411. }
  412. }
  413. }