ObjectExtension.cs 15 KB

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