StringHelper.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System.Collections;
  4. using System.Text;
  5. using System.Xml;
  6. namespace DopInterfacePlatform
  7. {
  8. public static class StringHelper
  9. {
  10. private static int[] numbers = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  11. /// <summary>
  12. /// 随机字符串数组集合
  13. /// </summary>
  14. private static readonly string[] NonceStrings = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
  15. /// <summary>
  16. /// 四舍五入取整数部分
  17. /// </summary>
  18. /// <param name="this"></param>
  19. /// <returns></returns>
  20. public static int StringToIntMathRound(this object @this)
  21. {
  22. string s_this = @this.ToString();
  23. int i_result = 0;
  24. if (s_this.Contains("."))
  25. {
  26. var tS =s_this.Split(".");
  27. i_result = Convert.ToInt32(tS[0]);
  28. if (Convert.ToInt32(tS[1].Substring(0, 1)) > 4)
  29. {
  30. i_result += 1;
  31. }
  32. }
  33. else
  34. {
  35. i_result = Convert.ToInt32(@this);
  36. }
  37. return i_result;
  38. }
  39. /// <summary>
  40. /// 生成指定长度的随机字符串
  41. /// </summary>
  42. /// <returns></returns>
  43. public static string CreateNonceStr(this int stringLenght)
  44. {
  45. Random random = new Random();
  46. var sb = new StringBuilder();
  47. var length = NonceStrings.Length;
  48. for (int i = 0; i < stringLenght; i++)
  49. {
  50. //通过random获得的随机索引到,NonceStrings数组中获取对应数组值
  51. sb.Append(NonceStrings[random.Next(length - 1)]);
  52. }
  53. return sb.ToString();
  54. }
  55. /// <summary>
  56. /// 获取指定长度的随机数
  57. /// </summary>
  58. /// <returns></returns>
  59. public static string GetRandom(this string @prexString, int lenght)
  60. {
  61. string result = prexString;
  62. Random rd = new Random();
  63. for (int i = 0; i < lenght - prexString.Length; i++)
  64. {
  65. int RandKey = rd.Next(100, 999);
  66. var index = RandKey % 10;
  67. result += numbers[index].ToString();
  68. }
  69. return result;
  70. }
  71. /// <summary>
  72. /// decimal取指定位小数返回
  73. /// </summary>
  74. /// <param name="this"></param>
  75. /// <param name="decimals"></param>
  76. /// <returns></returns>
  77. public static decimal DecimalsFormat(this decimal @this,int decimals=2)
  78. {
  79. return Math.Round(@this, decimals);
  80. }
  81. /// <summary>
  82. /// 涉及到金额部分把最后的0 去掉
  83. /// </summary>
  84. /// <param name="this"></param>
  85. /// <returns></returns>
  86. public static string CashFormat(this object @this)
  87. {
  88. string cashValue = @this.ToString();
  89. if (cashValue != null && cashValue.Contains(".")) //
  90. {
  91. while (cashValue.EndsWith("0"))
  92. {
  93. cashValue = cashValue.Substring(0, cashValue.Length - 1);
  94. }
  95. if (cashValue.EndsWith("."))
  96. cashValue = cashValue.Substring(0, cashValue.Length - 1);
  97. }
  98. return cashValue;
  99. }
  100. /// <summary>
  101. /// 判断是否为空
  102. /// </summary>
  103. /// <param name="this"></param>
  104. /// <returns></returns>
  105. public static bool IsNullOrWhiteSpace(this string @this)
  106. {
  107. if (@this == null) return true;
  108. return string.IsNullOrWhiteSpace(@this.Trim()) || @this == "null";
  109. }
  110. /// <summary>
  111. /// tostring的另一个版本,当是null字符串时返回空串
  112. /// </summary>
  113. /// <param name="this"></param>
  114. /// <returns></returns>
  115. public static string ToSelfOrNullString(this string @this)
  116. {
  117. if (@this == null) return "";
  118. return string.IsNullOrWhiteSpace(@this.Trim()) || @this == "null" ? "" : @this;
  119. }
  120. public static Hashtable GetProperties<T>(this T @userInfo)
  121. {
  122. Hashtable hashtable = new Hashtable();
  123. foreach (System.Reflection.PropertyInfo p in userInfo.GetType().GetProperties())
  124. {
  125. hashtable.Add(p.Name, p.GetValue(userInfo));
  126. }
  127. return hashtable;
  128. }
  129. /// <summary>
  130. /// 去掉Emoji表情
  131. /// </summary>
  132. /// <param name="this"></param>
  133. /// <returns></returns>
  134. public static string RemoveEmoji(this string @this)
  135. {
  136. foreach (var strTmp in @this)
  137. {
  138. byte[] bts = Encoding.UTF32.GetBytes(strTmp.ToString());
  139. if (bts[0].ToString() == "253"&& bts[1].ToString() == "255")
  140. {
  141. @this = @this.Replace(strTmp.ToString(), "");
  142. }
  143. }
  144. return @this;
  145. }
  146. /// <summary>
  147. /// 将Json字符串转换为对应的Json对象
  148. /// </summary>
  149. /// <typeparam name="T"></typeparam>
  150. /// <param name="this"></param>
  151. /// <returns></returns>
  152. public static T ToJsonObject<T>(this string @this)
  153. {
  154. return JsonConvert.DeserializeObject<T>(@this);
  155. }
  156. public static string DateTimeOfDayWeek(this string @this)
  157. {
  158. try
  159. {
  160. return ((int) Convert.ToDateTime(@this).DayOfWeek).ToString();
  161. }
  162. catch (Exception e)
  163. {
  164. return "";
  165. }
  166. }
  167. public static string YuanToFen(this string money)
  168. {
  169. return Convert.ToInt64(Convert.ToDecimal(money) * 100).ToString();
  170. }
  171. public static string FenToYuan(this int money)
  172. {
  173. return (Convert.ToDecimal(money)/100).ToString();
  174. }
  175. /// <summary>
  176. /// 将对象转换为string字符串
  177. /// </summary>
  178. /// <param name="this"></param>
  179. /// <returns></returns>
  180. public static string ToJsonString(this object @this)
  181. {
  182. return JsonConvert.SerializeObject(@this);
  183. }
  184. /// <summary>
  185. /// 排序字段
  186. /// </summary>
  187. /// <param name="this"></param>
  188. /// <returns></returns>
  189. public static Dictionary<string, object> SortDictionary(this Dictionary<string, object> @this)
  190. {
  191. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  192. foreach (var item in @this)
  193. {
  194. if (item.Value == null || item.Value.ToString() == "")
  195. {
  196. continue;
  197. }
  198. if(item.Key== "PatType")
  199. {
  200. }
  201. if (item.Value.GetType().Name == "JObject")
  202. {
  203. JObject j_object = item.Value as JObject;
  204. keyValues = keyValues.Concat(j_object.JObjectToDictionary()).ToDictionary(k => k.Key, v => v.Value);
  205. }
  206. else
  207. {
  208. keyValues.Add(item.Key, item.Value);
  209. }
  210. }
  211. return keyValues.OrderBy(p => p.Key).Where(d => d.Value != null).ToDictionary(p => p.Key, o => o.Value);
  212. }
  213. /// <summary>
  214. /// JObject to Dictionary<string, object>
  215. /// </summary>
  216. /// <param name="this"></param>
  217. /// <returns></returns>
  218. private static Dictionary<string, object> JObjectToDictionary(this JObject @this)
  219. {
  220. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  221. foreach (var item in @this)
  222. {
  223. keyValues.Add(item.Key, item.Value);
  224. //不考虑有多层的情况
  225. //if (item.Value.GetType().Name == "JObject")
  226. //{
  227. // JObject j_object = item.Value as JObject;
  228. // //还有子项目
  229. // keyValues = keyValues.Concat(j_object.JObjectToDictionary()).ToDictionary(k => k.Key, v => v.Value);
  230. //}
  231. //else
  232. //{
  233. // keyValues.Add(item.Key, item.Value);
  234. //}
  235. }
  236. return keyValues;
  237. }
  238. /// <summary>
  239. /// 转换成签名串
  240. /// </summary>
  241. /// <param name="this"></param>
  242. /// <returns></returns>
  243. public static string ToSignString(this object @this)
  244. {
  245. var objName = @this.GetType().Name;
  246. if (objName == "DateTime")
  247. {
  248. return Convert.ToDateTime(@this).ToString("yyyy-MM-dd HH:mm:ss");
  249. }
  250. else
  251. {
  252. return @this.ToString();
  253. }
  254. }
  255. /// <summary>
  256. /// BASE64编码
  257. /// </summary>
  258. /// <param name="un_code_string"></param>
  259. /// <param name="code_type"></param>
  260. /// <returns></returns>
  261. public static string EncodeBase64(this string un_code_string,string code_type= "utf-8")
  262. {
  263. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(un_code_string);
  264. string encode;
  265. try
  266. {
  267. encode = Convert.ToBase64String(bytes);
  268. }
  269. catch
  270. {
  271. encode = un_code_string;
  272. }
  273. return encode;
  274. }
  275. /// <summary>
  276. /// BASE64解码
  277. /// </summary>
  278. /// <param name="code_string"></param>
  279. /// <param name="code_type"></param>
  280. /// <returns></returns>
  281. public static string DecodeBase64(this string code_string,string code_type = "utf-8")
  282. {
  283. byte[] bytes = Convert.FromBase64String(code_string);
  284. string decode;
  285. try
  286. {
  287. decode = Encoding.GetEncoding(code_type).GetString(bytes);
  288. }
  289. catch
  290. {
  291. decode = code_string;
  292. }
  293. return decode;
  294. }
  295. /// <summary>
  296. /// xml格式的字符串转换成对象
  297. /// </summary>
  298. /// <param name="xmlStr"></param>
  299. /// <returns></returns>
  300. public static T XmlToObject<T>(this string xmlStr) where T : new()
  301. {
  302. try
  303. {
  304. T obj = new T();
  305. var repType = typeof(T);
  306. XmlDocument document = new XmlDocument();
  307. document.LoadXml(xmlStr); //加载Xml文件
  308. XmlElement node = document.DocumentElement; //xml的根标签
  309. var properties = repType.GetProperties();
  310. foreach (var itemProp in properties)
  311. {
  312. #region current type is List
  313. if (itemProp.PropertyType.FullName.Contains("System.Collections.Generic.List"))
  314. {
  315. object array = new object();
  316. var arryLength = 0;
  317. var notNullLength = 0;
  318. var arryType = itemProp.PropertyType.UnderlyingSystemType;
  319. var objList = itemProp.GetValue(obj, null) as System.Collections.IEnumerable;
  320. var enumt = objList.GetEnumerator();
  321. //enumt.
  322. var currentType = itemProp.PropertyType.GetGenericArguments()[0];
  323. foreach (XmlNode xmlitem in node.ChildNodes)
  324. {
  325. if (xmlitem.Name == itemProp.Name)
  326. {
  327. arryLength++;
  328. }
  329. }
  330. if (arryLength > 0)
  331. {
  332. var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList;
  333. foreach (XmlNode item in node.ChildNodes)
  334. {
  335. //current type is array
  336. if (item.Name == itemProp.Name)
  337. {
  338. var model = currentType.Assembly.CreateInstance(currentType.FullName); // arryType.GetElementType().Assembly.CreateInstance(currentType.FullName);
  339. SetArray(item.ChildNodes, model, true);
  340. arrayModel.Add(model);
  341. //arrayModel[notNullLength] = model;
  342. notNullLength++;
  343. }
  344. }
  345. itemProp.SetValue(obj, arrayModel, null);
  346. }
  347. continue;
  348. }
  349. #endregion
  350. var baseType = itemProp.PropertyType.BaseType.Name;
  351. if (baseType == "Array")
  352. {
  353. #region Current type is Array
  354. object array = new object();
  355. var arryLength = 0;
  356. var notNullLength = 0;
  357. var arryType = itemProp.PropertyType.UnderlyingSystemType;
  358. foreach (XmlNode xmlitem in node.ChildNodes)
  359. {
  360. if (xmlitem.Name == itemProp.Name && xmlitem.ChildNodes!=null && xmlitem.ChildNodes.Count>0)
  361. {
  362. arryLength++;
  363. }
  364. }
  365. if (arryLength > 0)
  366. {
  367. var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList;
  368. foreach (XmlNode item in node.ChildNodes)
  369. {
  370. //current type is array
  371. if (item.Name == itemProp.Name && item.ChildNodes!=null && item.ChildNodes.Count>0)
  372. {
  373. var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName);
  374. SetArray(item.ChildNodes, model);
  375. arrayModel[notNullLength] = model;
  376. notNullLength++;
  377. }
  378. }
  379. itemProp.SetValue(obj, arrayModel, null);
  380. }
  381. #endregion
  382. }
  383. else
  384. {
  385. #region Current type isn't Array
  386. foreach (XmlNode item in node.ChildNodes)
  387. {
  388. #region Current type is Number
  389. if (itemProp.Name == item.Name && (itemProp.PropertyType == typeof(long) || itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(string)))
  390. {
  391. if (itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(long))
  392. {
  393. if (!string.IsNullOrEmpty(item.InnerText))
  394. {
  395. if (itemProp.PropertyType == typeof(int))
  396. {
  397. itemProp.SetValue(obj, Convert.ToInt32(item.InnerText), null);
  398. }
  399. else
  400. {
  401. itemProp.SetValue(obj, Convert.ToInt64(item.InnerText), null);
  402. }
  403. }
  404. else
  405. {
  406. itemProp.SetValue(obj, 0, null);
  407. }
  408. }
  409. else
  410. {
  411. itemProp.SetValue(obj, item.InnerText, null);
  412. }
  413. }
  414. #endregion
  415. #region Current type is Model
  416. if (itemProp.PropertyType != typeof(long) && itemProp.PropertyType != typeof(string) && itemProp.PropertyType != typeof(int) && itemProp.PropertyType.Name == item.Name && item.HasChildNodes && item.FirstChild.NodeType == System.Xml.XmlNodeType.Element)
  417. {
  418. var modelType = itemProp.PropertyType.UnderlyingSystemType;
  419. var model = modelType.Assembly.CreateInstance(modelType.FullName);
  420. SetArray(item.ChildNodes, model);
  421. itemProp.SetValue(obj, model, null);
  422. }
  423. #endregion
  424. }
  425. #endregion
  426. }
  427. }
  428. repType = obj.GetType();
  429. return obj;
  430. }
  431. catch (Exception ex)
  432. {
  433. throw ex;
  434. }
  435. }
  436. #region Set array value
  437. private static Object SetArray(XmlNodeList xmlNodeList, object obj, bool isList = false)
  438. {
  439. try
  440. {
  441. var type = obj.GetType();
  442. var properties = type.GetProperties();
  443. foreach (var itemProp in properties)
  444. {
  445. //if (isList)
  446. if (itemProp.PropertyType.FullName.Contains("System.Collections.Generic.List"))
  447. {
  448. #region Current type is List
  449. object array = new object();
  450. var arryLength = 0;
  451. var notNullLength = 0;
  452. var arryType = itemProp.PropertyType.UnderlyingSystemType;
  453. var currentType = itemProp.PropertyType.GetGenericArguments()[0];
  454. foreach (XmlNode xmlitem in xmlNodeList)
  455. {
  456. if (xmlitem.Name == itemProp.Name)
  457. {
  458. arryLength++;
  459. }
  460. }
  461. if (arryLength > 0)
  462. {
  463. var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList;
  464. foreach (XmlNode item in xmlNodeList)
  465. {
  466. //current type is array
  467. if (item.Name == itemProp.Name)
  468. {
  469. var model = currentType.Assembly.CreateInstance(currentType.FullName); // var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName);
  470. SetArray(item.ChildNodes, model, true);
  471. arrayModel.Add(model);
  472. notNullLength++;
  473. }
  474. }
  475. itemProp.SetValue(obj, arrayModel, null);
  476. }
  477. #endregion
  478. return obj;
  479. }
  480. var baseType = itemProp.PropertyType.BaseType.Name;
  481. if (baseType == "Array")
  482. {
  483. #region Current type is Array
  484. object array = new object();
  485. var arryLength = 0;
  486. var notNullLength = 0;
  487. var arryType = itemProp.PropertyType.UnderlyingSystemType;
  488. foreach (XmlNode xmlitem in xmlNodeList)
  489. {
  490. if (xmlitem.Name == itemProp.Name)
  491. {
  492. arryLength++;
  493. }
  494. }
  495. if (arryLength > 0)
  496. {
  497. var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList;
  498. foreach (XmlNode item in xmlNodeList)
  499. {
  500. //current type is array
  501. if (item.Name == itemProp.Name)
  502. {
  503. var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName);
  504. SetArray(item.ChildNodes, model);
  505. arrayModel[notNullLength] = model;
  506. notNullLength++;
  507. }
  508. }
  509. itemProp.SetValue(obj, arrayModel, null);
  510. }
  511. #endregion
  512. }
  513. else
  514. {
  515. foreach (XmlNode item in xmlNodeList)
  516. {
  517. #region Current type is Number
  518. if (itemProp.Name == item.Name && (itemProp.PropertyType == typeof(long) || itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(string)))
  519. {
  520. if (itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(long))
  521. {
  522. if (!string.IsNullOrEmpty(item.InnerText))
  523. {
  524. if (itemProp.PropertyType == typeof(int))
  525. {
  526. itemProp.SetValue(obj, Convert.ToInt32(item.InnerText), null);
  527. }
  528. else
  529. {
  530. itemProp.SetValue(obj, Convert.ToInt64(item.InnerText), null);
  531. }
  532. }
  533. else
  534. {
  535. itemProp.SetValue(obj, 0, null);
  536. }
  537. }
  538. else
  539. {
  540. itemProp.SetValue(obj, item.InnerText, null);
  541. }
  542. }
  543. #endregion
  544. #region Current type is Model
  545. if (itemProp.PropertyType != typeof(long) && itemProp.PropertyType != typeof(int) && itemProp.PropertyType != typeof(string) && itemProp.PropertyType.Name == item.Name && item.HasChildNodes && item.FirstChild.NodeType == System.Xml.XmlNodeType.Element)
  546. {
  547. var modelType = itemProp.PropertyType.UnderlyingSystemType;
  548. var model = modelType.Assembly.CreateInstance(modelType.FullName);
  549. SetArray(item.ChildNodes, model);
  550. itemProp.SetValue(obj, model, null);
  551. }
  552. #endregion
  553. }
  554. }
  555. }
  556. }
  557. catch (Exception ex)
  558. {
  559. throw new Exception(ex.Message);
  560. }
  561. return obj;
  562. }
  563. #endregion
  564. }
  565. }