ObjectExtension.cs 17 KB

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