ConverHelper.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text.RegularExpressions;
  11. using System.Web;
  12. namespace Wms.Screen.Util.Comm
  13. {
  14. public class ConverHelper
  15. {
  16. #region object 转换T类型数据
  17. /// <summary>
  18. /// 转换 object为 T 类型
  19. /// </summary>
  20. /// <typeparam name="T">T 类型</typeparam>
  21. /// <param name="obj">object 数据</param>
  22. /// <param name="defVal">默认值</param>
  23. /// <param name="exp">是否抛出异常</param>
  24. /// <returns></returns>
  25. public static T ToTSource<T>(object obj, T defVal = default(T), bool exp = false)
  26. {
  27. T result = defVal;
  28. if (obj == null)
  29. {
  30. return result;
  31. }
  32. if (obj is T)
  33. {
  34. return (T)obj;
  35. }
  36. try
  37. {
  38. Type conversionType = typeof(T);
  39. object obj2 = null;
  40. if (conversionType.Equals(typeof(Guid)))
  41. obj2 = new Guid(Convert.ToString(obj));
  42. else
  43. obj2 = Convert.ChangeType(obj, conversionType);
  44. result = (T)obj2;
  45. }
  46. catch (Exception ex)
  47. {
  48. if (exp == true)
  49. {
  50. throw ex;
  51. }
  52. }
  53. return result;
  54. }
  55. #endregion
  56. #region 数值类型转换
  57. #region 转换为 bool 类型
  58. /// <summary>
  59. /// 将object转换为 bool 类型
  60. /// </summary>
  61. /// <param name="obj">待转换的object</param>
  62. /// <param name="defVal">缺省值(转换不成功)</param>
  63. /// <param name="exp">是否抛出异常(默认不抛出)</param>
  64. /// <returns>转换后的bool类型结果</returns>
  65. public static bool ToBool(object obj, bool defVal = false, bool exp = false)
  66. {
  67. bool result = defVal;
  68. try
  69. {
  70. if (obj != null)
  71. result = Convert.ToBoolean(obj);
  72. }
  73. catch (Exception ex)
  74. {
  75. if (exp == true)
  76. {
  77. throw ex;
  78. }
  79. }
  80. return result;
  81. }
  82. #endregion
  83. #region 转换为 Int 数值类型
  84. /// <summary>
  85. /// 将object转换Int 类型
  86. /// </summary>
  87. /// <param name="str">待转换的object</param>
  88. /// <param name="defVal">缺省值(转换不成功)</param>
  89. /// <param name="exp">是否抛出异常(默认不抛出)</param>
  90. /// <returns>转换后的Int类型结果</returns>
  91. public static int ToInt(object obj, int defVal = 0, bool exp = false)
  92. {
  93. int result = defVal;
  94. try
  95. {
  96. if (obj != null)
  97. result = Convert.ToInt32(obj);
  98. }
  99. catch (Exception ex)
  100. {
  101. if (exp == true)
  102. {
  103. throw ex;
  104. }
  105. }
  106. return result;
  107. }
  108. #endregion
  109. #region 转换为 Float 数值类型
  110. /// <summary>
  111. /// 将object转换 Float 类型
  112. /// </summary>
  113. /// <param name="str">待转换的object</param>
  114. /// <param name="defVal">缺省值(转换不成功)</param>
  115. /// <param name="exp">是否抛出异常(默认不抛出)</param>
  116. /// <returns>转换后的Int类型结果</returns>
  117. public static float ToFloat(object obj, float defVal = 0, bool exp = false)
  118. {
  119. float result = defVal;
  120. try
  121. {
  122. if (obj != null)
  123. result = Convert.ToSingle(obj);
  124. }
  125. catch (Exception ex)
  126. {
  127. if (exp == true)
  128. {
  129. throw ex;
  130. }
  131. }
  132. return result;
  133. }
  134. #endregion
  135. #region 转换为 Double 数值类型
  136. /// <summary>
  137. /// 将object转换 double 类型
  138. /// </summary>
  139. /// <param name="str">待转换的object</param>
  140. /// <param name="defVal">缺省值(转换不成功)</param>
  141. /// <param name="exp">是否抛出异常(默认不抛出)</param>
  142. /// <returns>转换后的Int类型结果</returns>
  143. public static double ToDouble(object obj, double defVal = 0, bool exp = false)
  144. {
  145. double result = defVal;
  146. try
  147. {
  148. if (obj != null)
  149. result = Convert.ToDouble(obj);
  150. }
  151. catch (Exception ex)
  152. {
  153. if (exp == true)
  154. {
  155. throw ex;
  156. }
  157. }
  158. return result;
  159. }
  160. #endregion
  161. #region 转换为 decimal 数值类型
  162. /// <summary>
  163. /// 将对象转换 decimal 类型
  164. /// </summary>
  165. /// <param name="obj">待转换的字符串</param>
  166. /// <param name="defVal">缺省值(转换不成功)</param>
  167. /// <param name="exp">是否抛出异常(默认不抛出)</param>
  168. /// <returns>转换后的decimal类型结果</returns>
  169. public static decimal ToDecimal(object obj, decimal defVal = 0m, bool exp = false)
  170. {
  171. decimal result = defVal;
  172. try
  173. {
  174. if (obj != null)
  175. result = Convert.ToDecimal(obj);
  176. }
  177. catch (Exception ex)
  178. {
  179. if (exp == true)
  180. {
  181. throw ex;
  182. }
  183. }
  184. return result;
  185. }
  186. #endregion
  187. #endregion
  188. #region 转换为 DateTime 日期类型
  189. /// <summary>
  190. /// 将object转换 DateTime 日期类型
  191. /// </summary>
  192. /// <param name="str">待转换的字符串</param>
  193. /// <param name="defVal">缺省值(转换不成功)</param>
  194. /// <param name="exp">是否抛出异常(默认不抛出)</param>
  195. /// <returns>转换后的DateTime类型结果</returns>
  196. public static DateTime ToDateTime(object obj, string defVal = "1970-01-01 08:00:00", bool exp = false)
  197. {
  198. DateTime result = DateTime.Parse(defVal);
  199. try
  200. {
  201. if (obj != null)
  202. result = Convert.ToDateTime(obj);
  203. }
  204. catch (Exception ex)
  205. {
  206. if (exp == true)
  207. {
  208. throw ex;
  209. }
  210. }
  211. return result;
  212. }
  213. #endregion
  214. #region DataTable 转 IList
  215. /// <summary>
  216. /// DataTable 转换 IList
  217. /// </summary>
  218. /// <typeparam name="TSource">model 类型</typeparam>
  219. /// <param name="dataTable">DataTable集合</param>
  220. /// <returns>List集合</returns>
  221. public static IList<TSource> ToList<TSource>(DataTable dataTable) where TSource : new()
  222. {
  223. var dataList = new List<TSource>();
  224. if (dataTable == null)
  225. {
  226. return null;
  227. }
  228. //创建一个属性的列表
  229. List<PropertyInfo> prlist = new List<PropertyInfo>();
  230. //获取TResult的类型实例 反射的入口
  231. Type t = typeof(TSource);
  232. //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
  233. Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dataTable.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
  234. foreach (DataRow row in dataTable.Rows)
  235. {
  236. //创建TResult的实例
  237. TSource ob = new TSource();
  238. //找到对应的数据 并赋值
  239. prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, ChangeType(row[p.Name], p.PropertyType), null); });
  240. //放入到返回的集合中.
  241. dataList.Add(ob);
  242. }
  243. return dataList;
  244. }
  245. /// 将数据转化为 type 类型
  246. /// </summary>
  247. /// <param name="value">要转化的值</param>
  248. /// <param name="type">目标类型</param>
  249. /// <returns>转化为目标类型的 Object 对象</returns>
  250. private static object ChangeType(object value, Type type)
  251. {
  252. if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
  253. {
  254. NullableConverter convertor = new NullableConverter(type);
  255. return Convert.IsDBNull(value) ? null : convertor.ConvertFrom(value);
  256. }
  257. return Convert.ChangeType(Convert.IsDBNull(value) ? null : value, type);
  258. }
  259. #endregion
  260. #region Json 解析操作 (引用 Newtonsoft.Json)
  261. /// <summary>
  262. /// object 转换 Json
  263. /// </summary>
  264. /// <param name="obj">源数据</param>
  265. /// <returns>json字符串</returns>
  266. public static string ToJson(object obj)
  267. {
  268. string json = JsonConvert.SerializeObject(obj);
  269. return json;
  270. }
  271. /// <summary>
  272. /// 解析Json字符串 生成实体对象
  273. /// </summary>
  274. /// <typeparam name="T">对象类型</typeparam>
  275. /// <param name="json">Json字符串</param>
  276. /// <returns>实体对象</returns>
  277. public static T JsonToObj<T>(string json) where T : class, new()
  278. {
  279. JsonSerializer js = new JsonSerializer();
  280. StringReader sr = new StringReader(json);
  281. object o = js.Deserialize(new JsonTextReader(sr), typeof(T));
  282. T result = o as T;
  283. return result;
  284. }
  285. /// <summary>
  286. /// 解析Json字符串 生成实体对象集合
  287. /// </summary>
  288. /// <typeparam name="T">对象类型</typeparam>
  289. /// <param name="json">Json字符串</param>
  290. /// <returns>实体对象集合</returns>
  291. public static IList<T> JsonToListObj<T>(string json) where T : class, new()
  292. {
  293. JsonSerializer js = new JsonSerializer();
  294. StringReader sr = new StringReader(json);
  295. object o = js.Deserialize(new JsonTextReader(sr), typeof(List<T>));
  296. IList<T> result = o as List<T>;
  297. return result;
  298. }
  299. /// <summary>
  300. /// 解析Json字符串 生成匿名对象
  301. /// </summary>
  302. /// <typeparam name="T">匿名对象</typeparam>
  303. /// <param name="json">Json字符串</param>
  304. /// <param name="anonymousTypeObject">匿名对象</param>
  305. /// <returns>匿名对象</returns>
  306. public static T JsonToAnonymous<T>(string json, T anonymousTypeObject)
  307. {
  308. T result = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
  309. return result;
  310. }
  311. #endregion
  312. #region 杂项转换
  313. #region 转换为 大写金额
  314. /// <summary>
  315. /// 将数值转换 RMB 大写金额
  316. /// </summary>
  317. /// <param name="money">待转换数值</param>
  318. /// <returns>大写金额</returns>
  319. public static string ToRMB(decimal money)
  320. {
  321. var s = money.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
  322. var d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\.]|$))))", "${b}${z}");
  323. var r = Regex.Replace(d, ".", m => "负元空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟万亿兆京垓秭穰"[m.Value[0] - '-'].ToString());
  324. return r;
  325. }
  326. #endregion
  327. #region 将客户端提交的值 转换 T 对象
  328. /// <summary>
  329. /// 将客户端提交的值 转换T对象
  330. /// </summary>
  331. /// <typeparam name="T">T 类型</typeparam>
  332. /// <param name="frmDats">Request.Form</param>
  333. /// <returns></returns>
  334. /// <example>
  335. /// <!--UserModel model = ConverHelper.To<UserModel>(context.Request.Form); -->
  336. /// </example>
  337. public static T FromToTSource<T>(NameValueCollection frmDats) where T : class, new()
  338. {
  339. Type type = typeof(T);
  340. string[] strArray = type.FullName.Split(new char[] { '.' });
  341. string cls = strArray[strArray.Length - 1];
  342. PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  343. T local = Activator.CreateInstance<T>();
  344. foreach (string data in frmDats.AllKeys)
  345. {
  346. string key = frmDats[data];
  347. if (!string.IsNullOrEmpty(key))
  348. key = key.TrimEnd(new char[0]);
  349. foreach (PropertyInfo info in properties)
  350. {
  351. string cls_name = string.Format("", cls, info.Name);
  352. if (data.Equals(info.Name, StringComparison.CurrentCultureIgnoreCase)
  353. || data.Equals(cls_name, StringComparison.CurrentCultureIgnoreCase))
  354. {
  355. string typeName = info.PropertyType.ToString();
  356. if (info.PropertyType.IsGenericType)
  357. {
  358. typeName = info.PropertyType.GetGenericArguments()[0].ToString();
  359. }
  360. object nullInternal = GetNullInternal(info.PropertyType);
  361. Type conversionType = Type.GetType(typeName, false);
  362. if (!string.IsNullOrEmpty(key))
  363. {
  364. nullInternal = Convert.ChangeType(key, conversionType);
  365. }
  366. info.SetValue(local, nullInternal, null);
  367. }
  368. }
  369. }
  370. return local;
  371. }
  372. /// <summary>
  373. /// 获取默认值
  374. /// </summary>
  375. /// <param name="type"></param>
  376. /// <returns></returns>
  377. private static object GetNullInternal(Type type)
  378. {
  379. if (type.IsValueType)
  380. {
  381. if (type.IsEnum)
  382. {
  383. return GetNullInternal(Enum.GetUnderlyingType(type));
  384. }
  385. if (type.IsPrimitive)
  386. {
  387. if (type == typeof(int))
  388. {
  389. return 0;
  390. }
  391. if (type == typeof(double))
  392. {
  393. return 0.0;
  394. }
  395. if (type == typeof(short))
  396. {
  397. return (short)0;
  398. }
  399. if (type == typeof(sbyte))
  400. {
  401. return (sbyte)0;
  402. }
  403. if (type == typeof(long))
  404. {
  405. return 0L;
  406. }
  407. if (type == typeof(byte))
  408. {
  409. return (byte)0;
  410. }
  411. if (type == typeof(ushort))
  412. {
  413. return (ushort)0;
  414. }
  415. if (type == typeof(uint))
  416. {
  417. return 0;
  418. }
  419. if (type == typeof(ulong))
  420. {
  421. return (ulong)0L;
  422. }
  423. if (type == typeof(ulong))
  424. {
  425. return (ulong)0L;
  426. }
  427. if (type == typeof(float))
  428. {
  429. return 0f;
  430. }
  431. if (type == typeof(bool))
  432. {
  433. return false;
  434. }
  435. if (type == typeof(char))
  436. {
  437. return '\0';
  438. }
  439. }
  440. else
  441. {
  442. if (type == typeof(DateTime))
  443. {
  444. return DateTime.MinValue;
  445. }
  446. if (type == typeof(decimal))
  447. {
  448. return 0M;
  449. }
  450. if (type == typeof(Guid))
  451. {
  452. return Guid.Empty;
  453. }
  454. if (type == typeof(TimeSpan))
  455. {
  456. return new TimeSpan(0, 0, 0);
  457. }
  458. }
  459. }
  460. return null;
  461. }
  462. #endregion
  463. #endregion
  464. #region 转换字符串
  465. /// <summary>
  466. /// 转换字符串,因为可能有空,直接转换会报错
  467. /// </summary>
  468. /// <param name="obj"></param>
  469. /// <param name="defVal"></param>
  470. /// <returns></returns>
  471. public static string ToString(object obj, string defVal = "")
  472. {
  473. string result = defVal;
  474. if (obj == null)
  475. {
  476. return result;
  477. }
  478. return obj.ToString();
  479. }
  480. #endregion
  481. public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
  482. {
  483. // 定义集合
  484. List<T> ts = new List<T>();
  485. //定义一个临时变量
  486. string tempName = string.Empty;
  487. //遍历DataTable中所有的数据行
  488. foreach (DataRow dr in dt.Rows)
  489. {
  490. T t = new T();
  491. // 获得此模型的公共属性
  492. PropertyInfo[] propertys = t.GetType().GetProperties();
  493. //遍历该对象的所有属性
  494. foreach (PropertyInfo pi in propertys)
  495. {
  496. tempName = pi.Name;//将属性名称赋值给临时变量
  497. //检查DataTable是否包含此列(列名==对象的属性名)
  498. if (dt.Columns.Contains(tempName))
  499. {
  500. //取值
  501. object value = dr[tempName];
  502. //如果非空,则赋给对象的属性
  503. if (value != DBNull.Value)
  504. {
  505. pi.SetValue(t, value, null);
  506. }
  507. }
  508. }
  509. //对象添加到泛型集合中
  510. ts.Add(t);
  511. }
  512. return ts;
  513. }
  514. }
  515. }