CommonExtend.cs 2.3 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. return false;
  48. }
  49. }
  50. public static T OpenXml<T>(this T t, string path)
  51. {
  52. try
  53. {
  54. System.Xml.Serialization.XmlSerializer xmlSerializer = new Xml.Serialization.XmlSerializer(t.GetType());
  55. System.IO.StreamReader fileStream = new IO.StreamReader(path);
  56. // YG.Log.Instance.WriteLogAdd(string.Format("反序列化对象:{0}成功 并写入文件:{1}", t.GetType(), path));
  57. t = (T)xmlSerializer.Deserialize(fileStream);
  58. fileStream.Close();
  59. return t;
  60. }
  61. catch (Exception ex)
  62. {
  63. return default(T);
  64. }
  65. }
  66. }
  67. }