ConvertService.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using Alchemy.Core.Extensions;
  2. using System.Reflection;
  3. namespace Alchemy.Core.Services
  4. {
  5. public class ConvertService
  6. {
  7. /// <summary>
  8. /// 字节数组转换为16进制表示的字符串
  9. /// </summary>
  10. public static string ByteArrayToHexString(byte[] buf)
  11. {
  12. string returnStr = string.Empty;
  13. if (buf.IsNotNull())
  14. {
  15. for (int i = 0; i < buf.Length; i++)
  16. {
  17. returnStr += buf[i].ToString("X2");
  18. }
  19. }
  20. return returnStr;
  21. }
  22. /// <summary>
  23. /// 类转换成IDic
  24. /// </summary>
  25. /// <param name="obj"></param>
  26. /// <returns></returns>
  27. public static Dictionary<string, string> ObjToDictionary(object obj)
  28. {
  29. Type type = obj.GetType();
  30. PropertyInfo[] properties = type.GetProperties();
  31. Dictionary<string, string> dict = new Dictionary<string, string>();
  32. foreach (PropertyInfo property in properties)
  33. {
  34. if (!property.CanRead || !property.CanWrite)
  35. continue;
  36. object value = property.GetValue(obj);
  37. string key = property.Name;
  38. string strValue = value?.ToString();
  39. dict[key] = strValue ?? string.Empty;
  40. }
  41. return dict;
  42. }
  43. }
  44. }