TypeExtension.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. using Newtonsoft.Json;
  2. using SqlSugar;
  3. using System.Collections.Concurrent;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Globalization;
  7. using System.Numerics;
  8. using System.Reflection;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. namespace ServiceCenter.Extensions
  13. {
  14. /// <summary>
  15. /// 类型转换扩展
  16. /// </summary>
  17. public static class TypeExtension
  18. {
  19. /// <summary>
  20. /// 将字符串转换为short
  21. /// </summary>
  22. /// <param name="value">需要转换的字符串</param>
  23. /// <returns></returns>
  24. public static short ToShort(this string value)
  25. {
  26. return Convert.ToInt16(value);
  27. }
  28. /// <summary>
  29. /// 将int转换为short
  30. /// </summary>
  31. /// <param name="value">需要转换的字符串</param>
  32. /// <returns></returns>
  33. public static short ToShort(this int value)
  34. {
  35. return Convert.ToInt16(value);
  36. }
  37. /// <summary>
  38. /// 将decimal转换为short
  39. /// </summary>
  40. /// <param name="value">需要转换的字符串</param>
  41. /// <returns></returns>
  42. public static short ToShort(this decimal value)
  43. {
  44. return Convert.ToInt16(value);
  45. }
  46. /// <summary>
  47. /// 将字符串转换为int
  48. /// </summary>
  49. /// <param name="value">需要转换的字符串</param>
  50. /// <returns></returns>
  51. public static int ToInt(this string value)
  52. {
  53. return Convert.ToInt32(value);
  54. }
  55. /// <summary>
  56. /// 获取最后一位数字
  57. /// </summary>
  58. /// <param name="value">字符串</param>
  59. /// <returns></returns>
  60. public static int GetLastDigit(this string value)
  61. {
  62. return Convert.ToInt32(Regex.Match(value, @"\d+$").Value);
  63. }
  64. /// <summary>
  65. /// 判断值为奇数/偶数
  66. /// </summary>
  67. /// <param name="value">需要判断的值</param>
  68. /// <returns> true:是奇数 false:是偶数</returns>
  69. public static bool OddNumberOrEven(this short value)
  70. {
  71. return value % 2 != 0;
  72. }
  73. /// <summary>
  74. /// 获取short类型Code,只限设备组
  75. /// </summary>
  76. /// <param name="value"></param>
  77. /// <returns></returns>
  78. public static short GetShortCode(this string value)
  79. {
  80. return value.Replace("G", "").ToShort();
  81. }
  82. /// <summary>
  83. /// 扩展方法,获得枚举的Description
  84. /// </summary>
  85. /// <param name="value">枚举值</param>
  86. /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
  87. /// <returns>枚举的Description</returns>
  88. public static string GetDescription(this Enum value, Boolean nameInstead = true)
  89. {
  90. Type type = value.GetType();
  91. string name = Enum.GetName(type, value);
  92. if (name == null)
  93. {
  94. return null;
  95. }
  96. FieldInfo field = type.GetField(name);
  97. DescriptionAttribute attribute = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
  98. if (attribute == null && nameInstead == true)
  99. {
  100. return name;
  101. }
  102. return attribute?.Description;
  103. }
  104. /// <summary>
  105. /// 获取属性的描述信息
  106. /// </summary>
  107. public static string GetDescription(this Type type, string proName)
  108. {
  109. PropertyInfo pro = type.GetProperty(proName);
  110. string des = proName;
  111. if (pro != null)
  112. {
  113. des = pro.GetDescription();
  114. }
  115. return des;
  116. }
  117. public static string JsonToString(this object value)
  118. {
  119. return JsonConvert.SerializeObject(value);
  120. }
  121. /// <summary>
  122. /// 获取属性的描述信息
  123. /// </summary>
  124. public static string GetDescription(this MemberInfo info)
  125. {
  126. var attrs = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
  127. string des = info.Name;
  128. foreach (DescriptionAttribute attr in attrs)
  129. {
  130. des = attr.Description;
  131. }
  132. return des;
  133. }
  134. /// <summary>
  135. /// 数据映射
  136. /// </summary>
  137. /// <typeparam name="D">映射目标实体Type</typeparam>
  138. /// <typeparam name="S"></typeparam>
  139. /// <param name="s"></param>
  140. /// <returns></returns>
  141. public static D Mapper<D, S>(this S s)
  142. {
  143. var d = Activator.CreateInstance<D>();
  144. var sType = s?.GetType();
  145. var dType = typeof(D);
  146. foreach (var sP in sType.GetProperties())
  147. {
  148. foreach (var dP in dType.GetProperties())
  149. {
  150. if (dP.Name == sP.Name)
  151. {
  152. dP.SetValue(d, sP.GetValue(s));
  153. break;
  154. }
  155. }
  156. }
  157. return d;
  158. }
  159. public static object Copy(this object obj, object type)
  160. {
  161. foreach (var p in type.GetType().GetProperties())
  162. {
  163. var p2 = obj.GetType().GetProperty(p.Name);
  164. if (p2 != null && p2.PropertyType == p.PropertyType)
  165. {
  166. var a = p2.GetValue(obj);
  167. p.SetValue(type, p2.GetValue(obj));
  168. }
  169. }
  170. return type;
  171. }
  172. public static object Copy(this object obj, Type type)
  173. {
  174. var res = Activator.CreateInstance(type);
  175. foreach (var p in type.GetProperties())
  176. {
  177. var p2 = obj.GetType().GetProperty(p.Name);
  178. if (p2 != null)
  179. {
  180. var value = p2.GetValue(obj);
  181. p.SetValue(res, value);
  182. }
  183. }
  184. return res;
  185. }
  186. //public static object Copy(this object source, Type t)
  187. //{
  188. // var obj = Activator.CreateInstance(t);
  189. // foreach (var p in t.GetProperties())
  190. // {
  191. // var p2 = source.GetType().GetProperty(p.Name);
  192. // var value = p2.GetValue(source);
  193. // p.SetValue(obj, value);
  194. // }
  195. // return obj;
  196. //}
  197. /// <summary>
  198. /// 获取字典
  199. /// </summary>
  200. /// <typeparam name="T1"></typeparam>
  201. /// <typeparam name="T2"></typeparam>
  202. /// <typeparam name="T3"></typeparam>
  203. /// <param name="t3"></param>
  204. /// <returns></returns>
  205. public static Dictionary<string, object> EntityClassToDictionary<T>(T t)
  206. {
  207. var type = typeof(SugarColumn);
  208. Dictionary<string, object> d = new Dictionary<string, object>();
  209. var sType = t.GetType();
  210. foreach (var sP in sType.GetProperties())
  211. {
  212. if (sP.CustomAttributes.Any(v => v.AttributeType == type) && sP.Name != "VER" && sP.Name != "ID")
  213. {
  214. d.Add(sP.Name, sP.GetValue(t));
  215. }
  216. }
  217. return d;
  218. }
  219. /// <summary>
  220. /// 获取MD5字符串
  221. /// </summary>
  222. /// <param name="myString"></param>
  223. /// <returns></returns>
  224. public static string GetMD5(this string myString)
  225. {
  226. var md5 = MD5.Create();
  227. var fromData = Encoding.Unicode.GetBytes(myString);
  228. var targetData = md5.ComputeHash(fromData);
  229. string byte2String = null;
  230. for (var i = 0; i < targetData.Length; i++)
  231. {
  232. byte2String += targetData[i].ToString("x");
  233. }
  234. return byte2String;
  235. }
  236. /// <summary>
  237. /// DataTable转换成实体类
  238. /// </summary>
  239. /// <typeparam name="T"></typeparam>
  240. /// <param name="dt"></param>
  241. /// <returns></returns>
  242. public static List<object> TableToEntity(this DataTable dt, string typeName)
  243. {
  244. var list = new List<object>();
  245. try
  246. {
  247. foreach (DataRow row in dt.Rows)
  248. {
  249. var entity = Type.GetType(typeName);
  250. PropertyInfo[] pArray = entity.GetType().GetProperties();
  251. foreach (var p in pArray)
  252. {
  253. if (dt.Columns.Contains(p.Name))
  254. {
  255. if (!p.CanWrite) continue;
  256. var value = row[p.Name];
  257. if (value != DBNull.Value)
  258. {
  259. var targetType = p.PropertyType;
  260. var convertType = targetType;
  261. if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
  262. {
  263. //可空类型
  264. var nullableConverter = new NullableConverter(targetType);
  265. convertType = nullableConverter.UnderlyingType;
  266. }
  267. if (!string.IsNullOrEmpty(convertType.FullName) && !string.IsNullOrEmpty(value.ToString()))
  268. {
  269. value = Convert.ChangeType(value, convertType);
  270. }
  271. switch (convertType.FullName)
  272. {
  273. case "System.Decimal":
  274. p.SetValue(entity, Convert.ToDecimal(value), null);
  275. break;
  276. case "System.String":
  277. p.SetValue(entity, Convert.ToString(value), null);
  278. break;
  279. case "System.Int32":
  280. p.SetValue(entity, Convert.ToInt32(value), null);
  281. break;
  282. case "System.Int64":
  283. p.SetValue(entity, Convert.ToInt64(value), null);
  284. break;
  285. case "System.Int16":
  286. p.SetValue(entity, Convert.ToInt16(value), null);
  287. break;
  288. case "System.Double":
  289. p.SetValue(entity, Convert.ToDouble(value), null);
  290. break;
  291. case "System.Single":
  292. p.SetValue(entity, Convert.ToSingle(value), null);
  293. break;
  294. case "System.DateTime":
  295. p.SetValue(entity, Convert.ToDateTime(value), null);
  296. break;
  297. default:
  298. p.SetValue(entity, value, null);
  299. break;
  300. }
  301. }
  302. }
  303. }
  304. list.Add(entity);
  305. }
  306. }
  307. catch (Exception ex)
  308. {
  309. }
  310. return list;
  311. }
  312. /// <summary>
  313. /// 转换到目标类型
  314. /// </summary>
  315. /// <param name="value"></param>
  316. /// <typeparam name="T"></typeparam>
  317. /// <returns></returns>
  318. internal static T ConvertTo<T>(this object value) => (T)typeof(T).FromObject(value);
  319. public static string yyyy(this DateTime time)
  320. {
  321. return time.GetFormat(GetFormatterEnum.yyyy);
  322. }
  323. public static string yyyyMM(this DateTime time)
  324. {
  325. return time.GetFormat(GetFormatterEnum.yyyyMM);
  326. }
  327. public static string yyyyMMdd(this DateTime time)
  328. {
  329. return time.GetFormat(GetFormatterEnum.yyyyMMdd);
  330. }
  331. public static string yyyyMMddhh(this DateTime time)
  332. {
  333. return time.GetFormat(GetFormatterEnum.yyyyMMddhh);
  334. }
  335. public static string yyyyMMddhhmm(this DateTime time)
  336. {
  337. return time.GetFormat(GetFormatterEnum.yyyyMMddhhmm);
  338. }
  339. public static string yyyyMMddhhmmss(this DateTime time)
  340. {
  341. return time.GetFormat(GetFormatterEnum.yyyyMMddhhmmss);
  342. }
  343. public static string yyyyMMddhhmmssf(this DateTime time)
  344. {
  345. return time.GetFormat(GetFormatterEnum.yyyyMMddhhmmssfffffff);
  346. }
  347. /// <summary>
  348. /// 获取指定格式时间的字符串
  349. /// </summary>
  350. /// <param name="time">时间</param>
  351. /// <param name="formatterEnum">类型</param>
  352. /// <returns></returns>
  353. public static string GetFormat(this DateTime time, GetFormatterEnum formatterEnum)
  354. {
  355. switch (formatterEnum)
  356. {
  357. case GetFormatterEnum.Default:
  358. return time.ToString();
  359. case GetFormatterEnum.yyyy:
  360. return time.ToString("yyyy");
  361. case GetFormatterEnum.yyyyMM:
  362. return time.ToString("yyyy-MM");
  363. case GetFormatterEnum.yyyyMMdd:
  364. return time.ToString("yyyy-MM-dd");
  365. case GetFormatterEnum.yyyyMMddhh:
  366. return time.ToString("yyyy-MM-dd HH");
  367. case GetFormatterEnum.yyyyMMddhhmm:
  368. return time.ToString("yyyy-MM-dd HH:mm");
  369. case GetFormatterEnum.yyyyMMddhhmmss:
  370. return time.ToString("yyyy-MM-dd HH:mm:ss");
  371. case GetFormatterEnum.yyyyMMddhhmmssfffffff:
  372. return time.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
  373. case GetFormatterEnum.only:
  374. return time.ToString("yyyyMMddHHmmssfffffff");
  375. default:
  376. return time.ToString();
  377. }
  378. }
  379. private static ConcurrentDictionary<Type, Func<string, object>> _dicFromObject = new ConcurrentDictionary<Type, Func<string, object>>();
  380. public static object FromObject(this Type targetType, object value, Encoding encoding = null)
  381. {
  382. if (targetType == typeof(object)) return value;
  383. if (encoding == null) encoding = Encoding.UTF8;
  384. var valueIsNull = value == null;
  385. var valueType = valueIsNull ? typeof(string) : value.GetType();
  386. if (valueType == targetType) return value;
  387. if (valueType == typeof(byte[])) //byte[] -> guid
  388. {
  389. if (targetType == typeof(Guid))
  390. {
  391. var bytes = value as byte[];
  392. return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
  393. }
  394. if (targetType == typeof(Guid?))
  395. {
  396. var bytes = value as byte[];
  397. return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
  398. }
  399. }
  400. if (targetType == typeof(byte[])) //guid -> byte[]
  401. {
  402. if (valueIsNull) return null;
  403. if (valueType == typeof(Guid) || valueType == typeof(Guid?))
  404. {
  405. var bytes = new byte[16];
  406. var guidN = ((Guid)value).ToString("N");
  407. for (var a = 0; a < guidN.Length; a += 2)
  408. bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
  409. return bytes;
  410. }
  411. return encoding.GetBytes(value.ToInvariantCultureToString());
  412. }
  413. else if (targetType.IsArray)
  414. {
  415. if (value is Array valueArr)
  416. {
  417. var targetElementType = targetType.GetElementType();
  418. var sourceArrLen = valueArr.Length;
  419. var target = Array.CreateInstance(targetElementType, sourceArrLen);
  420. for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
  421. return target;
  422. }
  423. //if (value is IList valueList)
  424. //{
  425. // var targetElementType = targetType.GetElementType();
  426. // var sourceArrLen = valueList.Count;
  427. // var target = Array.CreateInstance(targetElementType, sourceArrLen);
  428. // for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
  429. // return target;
  430. //}
  431. }
  432. var func = _dicFromObject.GetOrAdd(targetType, tt =>
  433. {
  434. if (tt == typeof(object)) return vs => vs;
  435. if (tt == typeof(string)) return vs => vs;
  436. if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
  437. if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
  438. if (tt == typeof(bool)) return vs =>
  439. {
  440. if (vs == null) return false;
  441. switch (vs.ToLower())
  442. {
  443. case "true":
  444. case "1":
  445. return true;
  446. }
  447. return false;
  448. };
  449. if (tt == typeof(bool?)) return vs =>
  450. {
  451. if (vs == null) return false;
  452. switch (vs.ToLower())
  453. {
  454. case "true":
  455. case "1":
  456. return true;
  457. case "false":
  458. case "0":
  459. return false;
  460. }
  461. return null;
  462. };
  463. if (tt == typeof(byte)) return vs => vs == null ? 0 : byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  464. if (tt == typeof(byte?)) return vs => vs == null ? null : byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null;
  465. if (tt == typeof(decimal)) return vs => vs == null ? 0 : decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  466. if (tt == typeof(decimal?)) return vs => vs == null ? null : decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null;
  467. if (tt == typeof(double)) return vs => vs == null ? 0 : double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  468. if (tt == typeof(double?)) return vs => vs == null ? null : double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null;
  469. if (tt == typeof(float)) return vs => vs == null ? 0 : float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  470. if (tt == typeof(float?)) return vs => vs == null ? null : float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null;
  471. if (tt == typeof(int)) return vs => vs == null ? 0 : int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  472. if (tt == typeof(int?)) return vs => vs == null ? null : int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null;
  473. if (tt == typeof(long)) return vs => vs == null ? 0 : long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  474. if (tt == typeof(long?)) return vs => vs == null ? null : long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null;
  475. if (tt == typeof(sbyte)) return vs => vs == null ? 0 : sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  476. if (tt == typeof(sbyte?)) return vs => vs == null ? null : sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null;
  477. if (tt == typeof(short)) return vs => vs == null ? 0 : short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  478. if (tt == typeof(short?)) return vs => vs == null ? null : short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null;
  479. if (tt == typeof(uint)) return vs => vs == null ? 0 : uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  480. if (tt == typeof(uint?)) return vs => vs == null ? null : uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null;
  481. if (tt == typeof(ulong)) return vs => vs == null ? 0 : ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  482. if (tt == typeof(ulong?)) return vs => vs == null ? null : ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null;
  483. if (tt == typeof(ushort)) return vs => vs == null ? 0 : ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  484. if (tt == typeof(ushort?)) return vs => vs == null ? null : ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null;
  485. if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue;
  486. if (tt == typeof(DateTime?)) return vs => vs == null ? null : DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null;
  487. if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue;
  488. if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null;
  489. if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero;
  490. if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null;
  491. if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty;
  492. if (tt == typeof(Guid?)) return vs => vs == null ? null : Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null;
  493. if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  494. if (tt == typeof(BigInteger?)) return vs => vs == null ? null : BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null;
  495. if (tt.NullableTypeOrThis().IsEnum)
  496. {
  497. var tttype = tt.NullableTypeOrThis();
  498. var ttdefval = tt.CreateInstanceGetDefaultValue();
  499. return vs =>
  500. {
  501. if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
  502. return Enum.Parse(tttype, vs, true);
  503. };
  504. }
  505. var localTargetType = targetType;
  506. var localValueType = valueType;
  507. return vs =>
  508. {
  509. if (vs == null) return null;
  510. throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
  511. };
  512. });
  513. var valueStr = valueIsNull ? null : valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString();
  514. return func(valueStr);
  515. }
  516. internal static string ToInvariantCultureToString(this object obj) => obj is string objstr ? objstr : string.Format(CultureInfo.InvariantCulture, @"{0}", obj);
  517. private static bool IsNullableType(this Type that) => that.IsArray == false && that?.FullName.StartsWith("System.Nullable`1[") == true;
  518. private static Type NullableTypeOrThis(this Type that) => that?.IsNullableType() == true ? that.GetGenericArguments().First() : that;
  519. internal static object CreateInstanceGetDefaultValue(this Type that)
  520. {
  521. if (that == null) return null;
  522. if (that == typeof(string)) return default(string);
  523. if (that == typeof(Guid)) return default(Guid);
  524. if (that == typeof(byte[])) return default(byte[]);
  525. if (that.IsArray) return Array.CreateInstance(that.GetElementType(), 0);
  526. if (that.IsInterface || that.IsAbstract) return null;
  527. var ctorParms = that.InternalGetTypeConstructor0OrFirst(false)?.GetParameters();
  528. if (ctorParms == null || ctorParms.Any() == false) return Activator.CreateInstance(that, true);
  529. return Activator.CreateInstance(that, ctorParms.Select(a => a.ParameterType.IsInterface ||
  530. a.ParameterType.IsAbstract ||
  531. a.ParameterType == typeof(string) ||
  532. a.ParameterType.IsArray ? null : Activator.CreateInstance(a.ParameterType, null)).ToArray());
  533. }
  534. private static ConcurrentDictionary<Type, ConstructorInfo> _dicInternalGetTypeConstructor0OrFirst = new ConcurrentDictionary<Type, ConstructorInfo>();
  535. private static ConstructorInfo InternalGetTypeConstructor0OrFirst(this Type that, bool isThrow = true)
  536. {
  537. var ret = _dicInternalGetTypeConstructor0OrFirst.GetOrAdd(that, tp =>
  538. tp.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null) ??
  539. tp.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault());
  540. if (ret == null && isThrow) throw new ArgumentException($"{that.FullName} has no method to access constructor");
  541. return ret;
  542. }
  543. private static string DisplayCsharp(this Type type, bool isNameSpace = true)
  544. {
  545. if (type == null) return null;
  546. if (type == typeof(void)) return "void";
  547. if (type.IsGenericParameter) return type.Name;
  548. if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
  549. var sb = new StringBuilder();
  550. var nestedType = type;
  551. while (nestedType.IsNested)
  552. {
  553. sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
  554. nestedType = nestedType.DeclaringType;
  555. }
  556. if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
  557. sb.Insert(0, ".").Insert(0, nestedType.Namespace);
  558. if (type.IsGenericType == false)
  559. return sb.Append(type.Name).ToString();
  560. var genericParameters = type.GetGenericArguments();
  561. if (type.IsNested && type.DeclaringType.IsGenericType)
  562. {
  563. var dic = genericParameters.ToDictionary(a => a.Name);
  564. foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
  565. if (dic.ContainsKey(nestedGenericParameter.Name))
  566. dic.Remove(nestedGenericParameter.Name);
  567. genericParameters = dic.Values.ToArray();
  568. }
  569. if (genericParameters.Any() == false)
  570. return sb.Append(type.Name).ToString();
  571. sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
  572. var genericTypeIndex = 0;
  573. foreach (var genericType in genericParameters)
  574. {
  575. if (genericTypeIndex++ > 0) sb.Append(", ");
  576. sb.Append(DisplayCsharp(genericType, true));
  577. }
  578. return sb.Append(">").ToString();
  579. }
  580. /// <summary>
  581. /// 对象转换为字典
  582. /// </summary>
  583. /// <typeparam name="T"></typeparam>
  584. /// <param name="obj"></param>
  585. /// <returns></returns>
  586. public static Dictionary<string, string> ToDic<T>(this T obj) where T : class
  587. {
  588. Dictionary<string, string> map = new Dictionary<string, string>();
  589. var objSte = JsonConvert.SerializeObject(obj);
  590. map = JsonConvert.DeserializeObject<Dictionary<string, string>>(objSte);
  591. return map;
  592. }
  593. /// <summary>
  594. /// 字典转为实体
  595. /// </summary>
  596. /// <typeparam name="T"></typeparam>
  597. /// <param name="obj"></param>
  598. /// <returns></returns>
  599. public static T ToClass<T>(this Dictionary<string, string> obj)
  600. {
  601. var objSte = JsonConvert.SerializeObject(obj);
  602. var map = JsonConvert.DeserializeObject<T>(objSte);
  603. return map;
  604. }
  605. }
  606. public enum GetFormatterEnum
  607. {
  608. /// <summary>
  609. /// 默认类型
  610. /// </summary>
  611. Default = 0,
  612. /// <summary>
  613. /// yyyy
  614. /// </summary>
  615. yyyy = 4,
  616. /// <summary>
  617. /// yyyy-MM
  618. /// </summary>
  619. yyyyMM = 5,
  620. /// <summary>
  621. /// yyyy-MM-dd
  622. /// </summary>
  623. yyyyMMdd = 6,
  624. /// <summary>
  625. /// yyyy-MM-dd hh
  626. /// </summary>
  627. yyyyMMddhh = 7,
  628. /// <summary>
  629. /// yyyy-MM-dd hh:mm
  630. /// </summary>
  631. yyyyMMddhhmm = 8,
  632. /// <summary>
  633. /// yyyy-MM-dd hh:mm:ss
  634. /// </summary>
  635. yyyyMMddhhmmss = 9,
  636. /// <summary>
  637. /// yyyy-MM-dd hh:mm:ss:fffffff
  638. /// </summary>
  639. yyyyMMddhhmmssfffffff = 10,
  640. /// <summary>
  641. /// 用时间组成唯一值
  642. /// yyyyMMddhhmmssfffffff
  643. /// </summary>
  644. only = 11,
  645. }
  646. }