TypeExtension.cs 29 KB

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