TypeExtension.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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, Type type)
  160. {
  161. var res = Activator.CreateInstance(type);
  162. foreach (var p in type.GetProperties())
  163. {
  164. var p2 = obj.GetType().GetProperty(p.Name);
  165. if (p2 != null && p2.PropertyType == p.PropertyType)
  166. {
  167. var a = p2.GetValue(obj);
  168. p.SetValue(res, p2.GetValue(obj));
  169. }
  170. }
  171. return res;
  172. }
  173. /// <summary>
  174. /// 获取字典
  175. /// </summary>
  176. /// <typeparam name="T1"></typeparam>
  177. /// <typeparam name="T2"></typeparam>
  178. /// <typeparam name="T3"></typeparam>
  179. /// <param name="t3"></param>
  180. /// <returns></returns>
  181. public static Dictionary<string, object> EntityClassToDictionary<T>(T t)
  182. {
  183. var type = typeof(SugarColumn);
  184. Dictionary<string, object> d = new Dictionary<string, object>();
  185. var sType = t.GetType();
  186. foreach (var sP in sType.GetProperties())
  187. {
  188. if (sP.CustomAttributes.Any(v => v.AttributeType == type) && sP.Name != "VER" && sP.Name != "ID")
  189. {
  190. d.Add(sP.Name, sP.GetValue(t));
  191. }
  192. }
  193. return d;
  194. }
  195. /// <summary>
  196. /// 获取MD5字符串
  197. /// </summary>
  198. /// <param name="myString"></param>
  199. /// <returns></returns>
  200. public static string GetMD5(this string myString)
  201. {
  202. var md5 = MD5.Create();
  203. var fromData = Encoding.Unicode.GetBytes(myString);
  204. var targetData = md5.ComputeHash(fromData);
  205. string byte2String = null;
  206. for (var i = 0; i < targetData.Length; i++)
  207. {
  208. byte2String += targetData[i].ToString("x");
  209. }
  210. return byte2String;
  211. }
  212. /// <summary>
  213. /// DataTable转换成实体类
  214. /// </summary>
  215. /// <typeparam name="T"></typeparam>
  216. /// <param name="dt"></param>
  217. /// <returns></returns>
  218. public static List<object> TableToEntity(this DataTable dt, string typeName)
  219. {
  220. var list = new List<object>();
  221. try
  222. {
  223. foreach (DataRow row in dt.Rows)
  224. {
  225. var entity = Type.GetType(typeName);
  226. PropertyInfo[] pArray = entity.GetType().GetProperties();
  227. foreach (var p in pArray)
  228. {
  229. if (dt.Columns.Contains(p.Name))
  230. {
  231. if (!p.CanWrite) continue;
  232. var value = row[p.Name];
  233. if (value != DBNull.Value)
  234. {
  235. var targetType = p.PropertyType;
  236. var convertType = targetType;
  237. if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
  238. {
  239. //可空类型
  240. var nullableConverter = new NullableConverter(targetType);
  241. convertType = nullableConverter.UnderlyingType;
  242. }
  243. if (!string.IsNullOrEmpty(convertType.FullName) && !string.IsNullOrEmpty(value.ToString()))
  244. {
  245. value = Convert.ChangeType(value, convertType);
  246. }
  247. switch (convertType.FullName)
  248. {
  249. case "System.Decimal":
  250. p.SetValue(entity, Convert.ToDecimal(value), null);
  251. break;
  252. case "System.String":
  253. p.SetValue(entity, Convert.ToString(value), null);
  254. break;
  255. case "System.Int32":
  256. p.SetValue(entity, Convert.ToInt32(value), null);
  257. break;
  258. case "System.Int64":
  259. p.SetValue(entity, Convert.ToInt64(value), null);
  260. break;
  261. case "System.Int16":
  262. p.SetValue(entity, Convert.ToInt16(value), null);
  263. break;
  264. case "System.Double":
  265. p.SetValue(entity, Convert.ToDouble(value), null);
  266. break;
  267. case "System.Single":
  268. p.SetValue(entity, Convert.ToSingle(value), null);
  269. break;
  270. case "System.DateTime":
  271. p.SetValue(entity, Convert.ToDateTime(value), null);
  272. break;
  273. default:
  274. p.SetValue(entity, value, null);
  275. break;
  276. }
  277. }
  278. }
  279. }
  280. list.Add(entity);
  281. }
  282. }
  283. catch (Exception ex)
  284. {
  285. }
  286. return list;
  287. }
  288. /// <summary>
  289. /// 转换到目标类型
  290. /// </summary>
  291. /// <param name="value"></param>
  292. /// <typeparam name="T"></typeparam>
  293. /// <returns></returns>
  294. internal static T ConvertTo<T>(this object value) => (T)typeof(T).FromObject(value);
  295. public static string yyyy(this DateTime time)
  296. {
  297. return time.GetFormat(GetFormatterEnum.yyyy);
  298. }
  299. public static string yyyyMM(this DateTime time)
  300. {
  301. return time.GetFormat(GetFormatterEnum.yyyyMM);
  302. }
  303. public static string yyyyMMdd(this DateTime time)
  304. {
  305. return time.GetFormat(GetFormatterEnum.yyyyMMdd);
  306. }
  307. public static string yyyyMMddhh(this DateTime time)
  308. {
  309. return time.GetFormat(GetFormatterEnum.yyyyMMddhh);
  310. }
  311. public static string yyyyMMddhhmm(this DateTime time)
  312. {
  313. return time.GetFormat(GetFormatterEnum.yyyyMMddhhmm);
  314. }
  315. public static string yyyyMMddhhmmss(this DateTime time)
  316. {
  317. return time.GetFormat(GetFormatterEnum.yyyyMMddhhmmss);
  318. }
  319. public static string yyyyMMddhhmmssf(this DateTime time)
  320. {
  321. return time.GetFormat(GetFormatterEnum.yyyyMMddhhmmssfffffff);
  322. }
  323. /// <summary>
  324. /// 获取指定格式时间的字符串
  325. /// </summary>
  326. /// <param name="time">时间</param>
  327. /// <param name="formatterEnum">类型</param>
  328. /// <returns></returns>
  329. public static string GetFormat(this DateTime time, GetFormatterEnum formatterEnum)
  330. {
  331. switch (formatterEnum)
  332. {
  333. case GetFormatterEnum.Default:
  334. return time.ToString();
  335. case GetFormatterEnum.yyyy:
  336. return time.ToString("yyyy");
  337. case GetFormatterEnum.yyyyMM:
  338. return time.ToString("yyyy-MM");
  339. case GetFormatterEnum.yyyyMMdd:
  340. return time.ToString("yyyy-MM-dd");
  341. case GetFormatterEnum.yyyyMMddhh:
  342. return time.ToString("yyyy-MM-dd HH");
  343. case GetFormatterEnum.yyyyMMddhhmm:
  344. return time.ToString("yyyy-MM-dd HH:mm");
  345. case GetFormatterEnum.yyyyMMddhhmmss:
  346. return time.ToString("yyyy-MM-dd HH:mm:ss");
  347. case GetFormatterEnum.yyyyMMddhhmmssfffffff:
  348. return time.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
  349. case GetFormatterEnum.only:
  350. return time.ToString("yyyyMMddHHmmssfffffff");
  351. default:
  352. return time.ToString();
  353. }
  354. }
  355. private static ConcurrentDictionary<Type, Func<string, object>> _dicFromObject = new ConcurrentDictionary<Type, Func<string, object>>();
  356. public static object FromObject(this Type targetType, object value, Encoding encoding = null)
  357. {
  358. if (targetType == typeof(object)) return value;
  359. if (encoding == null) encoding = Encoding.UTF8;
  360. var valueIsNull = value == null;
  361. var valueType = valueIsNull ? typeof(string) : value.GetType();
  362. if (valueType == targetType) return value;
  363. if (valueType == typeof(byte[])) //byte[] -> guid
  364. {
  365. if (targetType == typeof(Guid))
  366. {
  367. var bytes = value as byte[];
  368. return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
  369. }
  370. if (targetType == typeof(Guid?))
  371. {
  372. var bytes = value as byte[];
  373. return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
  374. }
  375. }
  376. if (targetType == typeof(byte[])) //guid -> byte[]
  377. {
  378. if (valueIsNull) return null;
  379. if (valueType == typeof(Guid) || valueType == typeof(Guid?))
  380. {
  381. var bytes = new byte[16];
  382. var guidN = ((Guid)value).ToString("N");
  383. for (var a = 0; a < guidN.Length; a += 2)
  384. bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
  385. return bytes;
  386. }
  387. return encoding.GetBytes(value.ToInvariantCultureToString());
  388. }
  389. else if (targetType.IsArray)
  390. {
  391. if (value is Array valueArr)
  392. {
  393. var targetElementType = targetType.GetElementType();
  394. var sourceArrLen = valueArr.Length;
  395. var target = Array.CreateInstance(targetElementType, sourceArrLen);
  396. for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
  397. return target;
  398. }
  399. //if (value is IList valueList)
  400. //{
  401. // var targetElementType = targetType.GetElementType();
  402. // var sourceArrLen = valueList.Count;
  403. // var target = Array.CreateInstance(targetElementType, sourceArrLen);
  404. // for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
  405. // return target;
  406. //}
  407. }
  408. var func = _dicFromObject.GetOrAdd(targetType, tt =>
  409. {
  410. if (tt == typeof(object)) return vs => vs;
  411. if (tt == typeof(string)) return vs => vs;
  412. if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
  413. if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
  414. if (tt == typeof(bool)) return vs =>
  415. {
  416. if (vs == null) return false;
  417. switch (vs.ToLower())
  418. {
  419. case "true":
  420. case "1":
  421. return true;
  422. }
  423. return false;
  424. };
  425. if (tt == typeof(bool?)) return vs =>
  426. {
  427. if (vs == null) return false;
  428. switch (vs.ToLower())
  429. {
  430. case "true":
  431. case "1":
  432. return true;
  433. case "false":
  434. case "0":
  435. return false;
  436. }
  437. return null;
  438. };
  439. if (tt == typeof(byte)) return vs => vs == null ? 0 : byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  440. if (tt == typeof(byte?)) return vs => vs == null ? null : byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null;
  441. if (tt == typeof(decimal)) return vs => vs == null ? 0 : decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  442. if (tt == typeof(decimal?)) return vs => vs == null ? null : decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null;
  443. if (tt == typeof(double)) return vs => vs == null ? 0 : double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  444. if (tt == typeof(double?)) return vs => vs == null ? null : double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null;
  445. if (tt == typeof(float)) return vs => vs == null ? 0 : float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  446. if (tt == typeof(float?)) return vs => vs == null ? null : float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null;
  447. if (tt == typeof(int)) return vs => vs == null ? 0 : int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  448. if (tt == typeof(int?)) return vs => vs == null ? null : int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null;
  449. if (tt == typeof(long)) return vs => vs == null ? 0 : long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  450. if (tt == typeof(long?)) return vs => vs == null ? null : long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null;
  451. if (tt == typeof(sbyte)) return vs => vs == null ? 0 : sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  452. if (tt == typeof(sbyte?)) return vs => vs == null ? null : sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null;
  453. if (tt == typeof(short)) return vs => vs == null ? 0 : short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  454. if (tt == typeof(short?)) return vs => vs == null ? null : short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null;
  455. if (tt == typeof(uint)) return vs => vs == null ? 0 : uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  456. if (tt == typeof(uint?)) return vs => vs == null ? null : uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null;
  457. if (tt == typeof(ulong)) return vs => vs == null ? 0 : ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  458. if (tt == typeof(ulong?)) return vs => vs == null ? null : ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null;
  459. if (tt == typeof(ushort)) return vs => vs == null ? 0 : ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  460. if (tt == typeof(ushort?)) return vs => vs == null ? null : ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null;
  461. if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue;
  462. if (tt == typeof(DateTime?)) return vs => vs == null ? null : DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null;
  463. if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue;
  464. if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null;
  465. if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero;
  466. if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null;
  467. if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty;
  468. if (tt == typeof(Guid?)) return vs => vs == null ? null : Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null;
  469. if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0;
  470. if (tt == typeof(BigInteger?)) return vs => vs == null ? null : BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null;
  471. if (tt.NullableTypeOrThis().IsEnum)
  472. {
  473. var tttype = tt.NullableTypeOrThis();
  474. var ttdefval = tt.CreateInstanceGetDefaultValue();
  475. return vs =>
  476. {
  477. if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
  478. return Enum.Parse(tttype, vs, true);
  479. };
  480. }
  481. var localTargetType = targetType;
  482. var localValueType = valueType;
  483. return vs =>
  484. {
  485. if (vs == null) return null;
  486. throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
  487. };
  488. });
  489. var valueStr = valueIsNull ? null : valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString();
  490. return func(valueStr);
  491. }
  492. internal static string ToInvariantCultureToString(this object obj) => obj is string objstr ? objstr : string.Format(CultureInfo.InvariantCulture, @"{0}", obj);
  493. private static bool IsNullableType(this Type that) => that.IsArray == false && that?.FullName.StartsWith("System.Nullable`1[") == true;
  494. private static Type NullableTypeOrThis(this Type that) => that?.IsNullableType() == true ? that.GetGenericArguments().First() : that;
  495. internal static object CreateInstanceGetDefaultValue(this Type that)
  496. {
  497. if (that == null) return null;
  498. if (that == typeof(string)) return default(string);
  499. if (that == typeof(Guid)) return default(Guid);
  500. if (that == typeof(byte[])) return default(byte[]);
  501. if (that.IsArray) return Array.CreateInstance(that.GetElementType(), 0);
  502. if (that.IsInterface || that.IsAbstract) return null;
  503. var ctorParms = that.InternalGetTypeConstructor0OrFirst(false)?.GetParameters();
  504. if (ctorParms == null || ctorParms.Any() == false) return Activator.CreateInstance(that, true);
  505. return Activator.CreateInstance(that, ctorParms.Select(a => a.ParameterType.IsInterface ||
  506. a.ParameterType.IsAbstract ||
  507. a.ParameterType == typeof(string) ||
  508. a.ParameterType.IsArray ? null : Activator.CreateInstance(a.ParameterType, null)).ToArray());
  509. }
  510. private static ConcurrentDictionary<Type, ConstructorInfo> _dicInternalGetTypeConstructor0OrFirst = new ConcurrentDictionary<Type, ConstructorInfo>();
  511. private static ConstructorInfo InternalGetTypeConstructor0OrFirst(this Type that, bool isThrow = true)
  512. {
  513. var ret = _dicInternalGetTypeConstructor0OrFirst.GetOrAdd(that, tp =>
  514. tp.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null) ??
  515. tp.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault());
  516. if (ret == null && isThrow) throw new ArgumentException($"{that.FullName} has no method to access constructor");
  517. return ret;
  518. }
  519. private static string DisplayCsharp(this Type type, bool isNameSpace = true)
  520. {
  521. if (type == null) return null;
  522. if (type == typeof(void)) return "void";
  523. if (type.IsGenericParameter) return type.Name;
  524. if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
  525. var sb = new StringBuilder();
  526. var nestedType = type;
  527. while (nestedType.IsNested)
  528. {
  529. sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
  530. nestedType = nestedType.DeclaringType;
  531. }
  532. if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
  533. sb.Insert(0, ".").Insert(0, nestedType.Namespace);
  534. if (type.IsGenericType == false)
  535. return sb.Append(type.Name).ToString();
  536. var genericParameters = type.GetGenericArguments();
  537. if (type.IsNested && type.DeclaringType.IsGenericType)
  538. {
  539. var dic = genericParameters.ToDictionary(a => a.Name);
  540. foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
  541. if (dic.ContainsKey(nestedGenericParameter.Name))
  542. dic.Remove(nestedGenericParameter.Name);
  543. genericParameters = dic.Values.ToArray();
  544. }
  545. if (genericParameters.Any() == false)
  546. return sb.Append(type.Name).ToString();
  547. sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
  548. var genericTypeIndex = 0;
  549. foreach (var genericType in genericParameters)
  550. {
  551. if (genericTypeIndex++ > 0) sb.Append(", ");
  552. sb.Append(DisplayCsharp(genericType, true));
  553. }
  554. return sb.Append(">").ToString();
  555. }
  556. /// <summary>
  557. /// 对象转换为字典
  558. /// </summary>
  559. /// <typeparam name="T"></typeparam>
  560. /// <param name="obj"></param>
  561. /// <returns></returns>
  562. public static Dictionary<string, string> ToDic<T>(this T obj) where T : class
  563. {
  564. Dictionary<string, string> map = new Dictionary<string, string>();
  565. var objSte = JsonConvert.SerializeObject(obj);
  566. map = JsonConvert.DeserializeObject<Dictionary<string, string>>(objSte);
  567. return map;
  568. }
  569. /// <summary>
  570. /// 字典转为实体
  571. /// </summary>
  572. /// <typeparam name="T"></typeparam>
  573. /// <param name="obj"></param>
  574. /// <returns></returns>
  575. public static T ToClass<T>(this Dictionary<string, string> obj)
  576. {
  577. var objSte = JsonConvert.SerializeObject(obj);
  578. var map = JsonConvert.DeserializeObject<T>(objSte);
  579. return map;
  580. }
  581. }
  582. public enum GetFormatterEnum
  583. {
  584. /// <summary>
  585. /// 默认类型
  586. /// </summary>
  587. Default = 0,
  588. /// <summary>
  589. /// yyyy
  590. /// </summary>
  591. yyyy = 4,
  592. /// <summary>
  593. /// yyyy-MM
  594. /// </summary>
  595. yyyyMM = 5,
  596. /// <summary>
  597. /// yyyy-MM-dd
  598. /// </summary>
  599. yyyyMMdd = 6,
  600. /// <summary>
  601. /// yyyy-MM-dd hh
  602. /// </summary>
  603. yyyyMMddhh = 7,
  604. /// <summary>
  605. /// yyyy-MM-dd hh:mm
  606. /// </summary>
  607. yyyyMMddhhmm = 8,
  608. /// <summary>
  609. /// yyyy-MM-dd hh:mm:ss
  610. /// </summary>
  611. yyyyMMddhhmmss = 9,
  612. /// <summary>
  613. /// yyyy-MM-dd hh:mm:ss:fffffff
  614. /// </summary>
  615. yyyyMMddhhmmssfffffff = 10,
  616. /// <summary>
  617. /// 用时间组成唯一值
  618. /// yyyyMMddhhmmssfffffff
  619. /// </summary>
  620. only = 11,
  621. }
  622. }