ObjectExtension.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. /// 是否有值
  230. /// </summary>
  231. /// <param name="obj"></param>
  232. /// <returns></returns>
  233. public static bool IsNullOrEmpty(this object obj)
  234. {
  235. return obj == null || string.IsNullOrEmpty(obj.ToString());
  236. }
  237. /// <summary>
  238. /// 字符串掩码
  239. /// </summary>
  240. /// <param name="str">字符串</param>
  241. /// <param name="mask">掩码符</param>
  242. /// <returns></returns>
  243. public static string Mask(this string str, char mask = '*')
  244. {
  245. if (string.IsNullOrWhiteSpace(str?.Trim()))
  246. return str;
  247. str = str.Trim();
  248. var masks = mask.ToString().PadLeft(4, mask);
  249. return str.Length switch
  250. {
  251. >= 11 => Regex.Replace(str, "(.{3}).*(.{4})", $"$1{masks}$2"),
  252. 10 => Regex.Replace(str, "(.{3}).*(.{3})", $"$1{masks}$2"),
  253. 9 => Regex.Replace(str, "(.{2}).*(.{3})", $"$1{masks}$2"),
  254. 8 => Regex.Replace(str, "(.{2}).*(.{2})", $"$1{masks}$2"),
  255. 7 => Regex.Replace(str, "(.{1}).*(.{2})", $"$1{masks}$2"),
  256. 6 => Regex.Replace(str, "(.{1}).*(.{1})", $"$1{masks}$2"),
  257. _ => Regex.Replace(str, "(.{1}).*", $"$1{masks}")
  258. };
  259. }
  260. /// <summary>
  261. /// 身份证号掩码
  262. /// </summary>
  263. /// <param name="idCard">身份证号</param>
  264. /// <param name="mask">掩码符</param>
  265. /// <returns></returns>
  266. public static string MaskIdCard(this string idCard, char mask = '*')
  267. {
  268. if (!idCard.TryValidate(ValidationTypes.IDCard).IsValid) return idCard;
  269. var masks = mask.ToString().PadLeft(8, mask);
  270. return Regex.Replace(idCard, @"^(.{6})(.*)(.{4})$", $"$1{masks}$3");
  271. }
  272. /// <summary>
  273. /// 邮箱掩码
  274. /// </summary>
  275. /// <param name="email">邮箱</param>
  276. /// <param name="mask">掩码符</param>
  277. /// <returns></returns>
  278. public static string MaskEmail(this string email, char mask = '*')
  279. {
  280. if (!email.TryValidate(ValidationTypes.EmailAddress).IsValid) return email;
  281. var masks = mask.ToString().PadLeft(4, mask);
  282. return email.Replace(@"^([^\.]+)\.?", $"$1{masks}$2");
  283. }
  284. }