ObjectExtension.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
  2. namespace Admin.NET.Core;
  3. /// <summary>
  4. /// 对象拓展
  5. /// </summary>
  6. [SuppressSniffer]
  7. public static partial class ObjectExtension
  8. {
  9. /// <summary>
  10. /// 判断类型是否实现某个泛型
  11. /// </summary>
  12. /// <param name="type">类型</param>
  13. /// <param name="generic">泛型类型</param>
  14. /// <returns>bool</returns>
  15. public static bool HasImplementedRawGeneric(this Type type, Type generic)
  16. {
  17. // 检查接口类型
  18. var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
  19. if (isTheRawGenericType) return true;
  20. // 检查类型
  21. while (type != null && type != typeof(object))
  22. {
  23. isTheRawGenericType = IsTheRawGenericType(type);
  24. if (isTheRawGenericType) return true;
  25. type = type.BaseType;
  26. }
  27. return false;
  28. // 判断逻辑
  29. bool IsTheRawGenericType(Type type) => generic == (type.IsGenericType ? type.GetGenericTypeDefinition() : type);
  30. }
  31. /// <summary>
  32. /// 将字典转化为QueryString格式
  33. /// </summary>
  34. /// <param name="dict"></param>
  35. /// <param name="urlEncode"></param>
  36. /// <returns></returns>
  37. public static string ToQueryString(this Dictionary<string, string> dict, bool urlEncode = true)
  38. {
  39. return string.Join("&", dict.Select(p => $"{(urlEncode ? p.Key?.UrlEncode() : "")}={(urlEncode ? p.Value?.UrlEncode() : "")}"));
  40. }
  41. /// <summary>
  42. /// 将字符串URL编码
  43. /// </summary>
  44. /// <param name="str"></param>
  45. /// <returns></returns>
  46. public static string UrlEncode(this string str)
  47. {
  48. return string.IsNullOrEmpty(str) ? "" : System.Web.HttpUtility.UrlEncode(str, Encoding.UTF8);
  49. }
  50. /// <summary>
  51. /// List转DataTable
  52. /// </summary>
  53. /// <typeparam name="T"></typeparam>
  54. /// <param name="list"></param>
  55. /// <returns></returns>
  56. public static DataTable ToDataTable<T>(this List<T> list)
  57. {
  58. DataTable dt = new();
  59. if (list.Count <= 0) return dt;
  60. // result.TableName = list[0].GetType().Name; // 表名赋值
  61. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  62. foreach (PropertyInfo pi in propertys)
  63. {
  64. if (IsIgnoreColumn(pi))
  65. continue;
  66. var colType = pi.PropertyType.IsGenericType ? pi.PropertyType.GetGenericArguments()[0] : pi.PropertyType;
  67. dt.Columns.Add(pi.Name, colType);
  68. }
  69. for (int i = 0; i < list.Count; i++)
  70. {
  71. ArrayList tempList = new();
  72. foreach (PropertyInfo pi in propertys)
  73. {
  74. if (IsIgnoreColumn(pi))
  75. continue;
  76. tempList.Add(pi.GetValue(list[i], null));
  77. }
  78. dt.LoadDataRow(tempList.ToArray(), true);
  79. }
  80. // 删除空列
  81. foreach (var column in dt.Columns.Cast<DataColumn>().ToArray())
  82. {
  83. if (dt.AsEnumerable().All(dr => dr.IsNull(column)))
  84. dt.Columns.Remove(column);
  85. }
  86. return dt;
  87. }
  88. /// <summary>
  89. /// 对象序列化成Json字符串
  90. /// </summary>
  91. /// <param name="obj"></param>
  92. /// <returns></returns>
  93. public static string ToJson(this object obj)
  94. {
  95. return JSON.GetJsonSerializer().Serialize(obj);
  96. }
  97. /// <summary>
  98. /// Json字符串反序列化成对象
  99. /// </summary>
  100. /// <typeparam name="T"></typeparam>
  101. /// <param name="json"></param>
  102. /// <returns></returns>
  103. public static T ToObject<T>(this string json)
  104. {
  105. return JSON.GetJsonSerializer().Deserialize<T>(json);
  106. }
  107. /// <summary>
  108. /// 排除SqlSugar忽略的列
  109. /// </summary>
  110. /// <param name="pi"></param>
  111. /// <returns></returns>
  112. private static bool IsIgnoreColumn(PropertyInfo pi)
  113. {
  114. var sc = pi.GetCustomAttributes<SugarColumn>(false).FirstOrDefault(u => u.IsIgnore == true);
  115. return sc != null;
  116. }
  117. /// <summary>
  118. /// 将object转换为long,若失败则返回0
  119. /// </summary>
  120. /// <param name="obj"></param>
  121. /// <returns></returns>
  122. public static long ParseToLong(this object obj)
  123. {
  124. try
  125. {
  126. return long.Parse(obj.ToString());
  127. }
  128. catch
  129. {
  130. return 0L;
  131. }
  132. }
  133. /// <summary>
  134. /// 将object转换为long,若失败则返回指定值
  135. /// </summary>
  136. /// <param name="str"></param>
  137. /// <param name="defaultValue"></param>
  138. /// <returns></returns>
  139. public static long ParseToLong(this string str, long defaultValue)
  140. {
  141. try
  142. {
  143. return long.Parse(str);
  144. }
  145. catch
  146. {
  147. return defaultValue;
  148. }
  149. }
  150. /// <summary>
  151. /// 将object转换为double,若失败则返回0
  152. /// </summary>
  153. /// <param name="obj"></param>
  154. /// <returns></returns>
  155. public static double ParseToDouble(this object obj)
  156. {
  157. try
  158. {
  159. return double.Parse(obj.ToString());
  160. }
  161. catch
  162. {
  163. return 0;
  164. }
  165. }
  166. /// <summary>
  167. /// 将object转换为double,若失败则返回指定值
  168. /// </summary>
  169. /// <param name="str"></param>
  170. /// <param name="defaultValue"></param>
  171. /// <returns></returns>
  172. public static double ParseToDouble(this object str, double defaultValue)
  173. {
  174. try
  175. {
  176. return double.Parse(str.ToString());
  177. }
  178. catch
  179. {
  180. return defaultValue;
  181. }
  182. }
  183. /// <summary>
  184. /// 将string转换为DateTime,若失败则返回日期最小值
  185. /// </summary>
  186. /// <param name="str"></param>
  187. /// <returns></returns>
  188. public static DateTime ParseToDateTime(this string str)
  189. {
  190. try
  191. {
  192. if (string.IsNullOrWhiteSpace(str))
  193. {
  194. return DateTime.MinValue;
  195. }
  196. if (str.Contains("-") || str.Contains("/"))
  197. {
  198. return DateTime.Parse(str);
  199. }
  200. else
  201. {
  202. int length = str.Length;
  203. switch (length)
  204. {
  205. case 4:
  206. return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
  207. case 6:
  208. return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
  209. case 8:
  210. return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
  211. case 10:
  212. return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
  213. case 12:
  214. return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
  215. case 14:
  216. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  217. default:
  218. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  219. }
  220. }
  221. }
  222. catch
  223. {
  224. return DateTime.MinValue;
  225. }
  226. }
  227. /// <summary>
  228. /// 将string转换为DateTime,若失败则返回默认值
  229. /// </summary>
  230. /// <param name="str"></param>
  231. /// <param name="defaultValue"></param>
  232. /// <returns></returns>
  233. public static DateTime ParseToDateTime(this string str, DateTime? defaultValue)
  234. {
  235. try
  236. {
  237. if (string.IsNullOrWhiteSpace(str))
  238. {
  239. return defaultValue.GetValueOrDefault();
  240. }
  241. if (str.Contains("-") || str.Contains("/"))
  242. {
  243. return DateTime.Parse(str);
  244. }
  245. else
  246. {
  247. int length = str.Length;
  248. switch (length)
  249. {
  250. case 4:
  251. return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
  252. case 6:
  253. return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
  254. case 8:
  255. return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
  256. case 10:
  257. return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
  258. case 12:
  259. return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
  260. case 14:
  261. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  262. default:
  263. return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
  264. }
  265. }
  266. }
  267. catch
  268. {
  269. return defaultValue.GetValueOrDefault();
  270. }
  271. }
  272. }