ObjectExtend.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* ==============================================================================
  2. * 功能描述:ObjectExtend
  3. * 创 建 者:Garrett
  4. * 创建日期:2017/10/16 16:55:19
  5. * ==============================================================================*/
  6. using System;
  7. using System.ComponentModel;
  8. using System.Reflection;
  9. namespace SAGA.DotNetUtils.Extend
  10. {
  11. /// <summary>
  12. /// ObjectExtend
  13. /// </summary>
  14. public static class ObjectExtend
  15. {
  16. /// <summary>
  17. /// 转为String
  18. /// </summary>
  19. /// <param name="obj"></param>
  20. /// <returns></returns>
  21. public static string ToStr(this object obj)
  22. {
  23. string result = "";
  24. if (obj != null)
  25. {
  26. try
  27. {
  28. result = Convert.ToString(obj);
  29. }
  30. catch (Exception e)
  31. {
  32. }
  33. }
  34. return result;
  35. }
  36. public static bool IsNullOrEmpty(this object obj)
  37. {
  38. return obj==null||((string) obj)=="";
  39. }
  40. public static bool IsNotNullEmpty(this object obj)
  41. {
  42. return !obj.IsNullOrEmpty();
  43. }
  44. /// <summary>
  45. /// 通过反射对有DescriptionAttribute标记的属性进行赋值
  46. /// </summary>
  47. /// <typeparam name="T"></typeparam>
  48. /// <param name="mode"></param>
  49. /// <param name="values"></param>
  50. /// <param name="func"></param>
  51. /// <returns></returns>
  52. public static void ReflectSetPropertyValue<T>(this T mode, object values, Func<object, string, string> func)
  53. {
  54. foreach (PropertyInfo property in mode.GetType().GetProperties())
  55. {
  56. var description = property.GetCustomAttribute<DescriptionAttribute>()?.Description;
  57. string value = "";
  58. try
  59. {
  60. value = func.Invoke(values,description);
  61. }
  62. catch (Exception e)
  63. {
  64. }
  65. if (value.IsNotNullEmpty())
  66. {
  67. object obj = Convert.ChangeType(value, property.PropertyType);
  68. property.SetValue(mode, obj);
  69. }
  70. }
  71. }
  72. }
  73. }