CommonExtend.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace System.Text
  7. {
  8. public static class CommonExtend
  9. {
  10. public static string EnumToString<T>(this Enum @enum)
  11. {
  12. return Enum.GetName(typeof(T), @enum);
  13. }
  14. public static T GetEnum<T>(this string value)
  15. {
  16. return value.StringIsEmpty() ? default(T) : (T)Enum.Parse(typeof(T), value);
  17. }
  18. public static short GetShort(this byte[] bt, int index)
  19. {
  20. int itemnumber = 0;
  21. itemnumber = bt[index];
  22. itemnumber <<= 8;
  23. itemnumber = bt[index+1] | itemnumber;
  24. return (short)itemnumber;
  25. }
  26. public static string ToClone(this string value)
  27. {
  28. return value.Clone().ToString();
  29. }
  30. public static bool SaveXml<T>(this T t, string path)
  31. {
  32. try
  33. {
  34. if (t == null)
  35. {
  36. return false;
  37. }
  38. System.Xml.Serialization.XmlSerializer xmlSerializer = new Xml.Serialization.XmlSerializer(t.GetType());
  39. System.IO.StreamWriter fileStream = new IO.StreamWriter(path, false);
  40. xmlSerializer.Serialize(fileStream, t);
  41. fileStream.Close();
  42. // YG.Log.Instance.WriteLogAdd(string.Format("序列化对象:{0}成功 并写入文件:{1}", t.GetType(), path));
  43. return true;
  44. }
  45. catch (Exception ex)
  46. {
  47. YG.Log.Instance.WriteLogAdd(string.Format("序列化对象:{0}失败:{1}", t.GetType(), ex.Message));
  48. return false;
  49. }
  50. }
  51. public static T OpenXml<T>(this T t, string path)
  52. {
  53. try
  54. {
  55. System.Xml.Serialization.XmlSerializer xmlSerializer = new Xml.Serialization.XmlSerializer(t.GetType());
  56. System.IO.StreamReader fileStream = new IO.StreamReader(path);
  57. // YG.Log.Instance.WriteLogAdd(string.Format("反序列化对象:{0}成功 并写入文件:{1}", t.GetType(), path));
  58. t = (T)xmlSerializer.Deserialize(fileStream);
  59. fileStream.Close();
  60. return t;
  61. }
  62. catch (Exception ex)
  63. {
  64. YG.Log.Instance.WriteLogAdd(string.Format("反序列化对象:{0}失败:{1}", t.GetType(), ex.Message));
  65. return default(T);
  66. }
  67. }
  68. }
  69. }