ObjectReflection.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace NXWMS.Code.Reflections
  8. {
  9. // <summary>
  10. /// 反射赋值
  11. /// </summary>
  12. public static class ObjectReflection
  13. {
  14. public static PropertyInfo[] GetPropertyInfos(Type type)
  15. {
  16. return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  17. }
  18. /// <summary>
  19. /// 实体属性反射
  20. /// </summary>
  21. /// <typeparam name="S">赋值对象</typeparam>
  22. /// <typeparam name="T">被赋值对象</typeparam>
  23. /// <param name="s"></param>
  24. /// <param name="t"></param>
  25. public static void AutoMapping<S, T>(S s, T t)
  26. {
  27. PropertyInfo[] pps = GetPropertyInfos(s.GetType());
  28. Type target = t.GetType();
  29. foreach (var pp in pps)
  30. {
  31. PropertyInfo targetPP = target.GetProperty(pp.Name);
  32. object value = pp.GetValue(s, null);
  33. if (targetPP != null && value != null)
  34. {
  35. targetPP.SetValue(t, value, null);
  36. }
  37. }
  38. }
  39. /// <summary>
  40. /// 设置类中属性
  41. /// </summary>
  42. /// <typeparam name="T"></typeparam>
  43. /// <param name="t"></param>
  44. /// <param name="fieldName"></param>
  45. /// <param name="value"></param>
  46. /// <returns></returns>
  47. public static string SetFieldValue<T>(T t,string fieldName,object value) where T: class
  48. {
  49. try
  50. {
  51. var type = t.GetType();
  52. var propertyInfo = type.GetProperty(fieldName);
  53. propertyInfo.SetValue(t, value, null);
  54. return string.Empty;
  55. }
  56. catch(Exception ex)
  57. {
  58. return ex.Message;
  59. }
  60. }
  61. /// <summary>
  62. /// 获取类中属性
  63. /// </summary>
  64. /// <param name="FieldName"></param>
  65. /// <param name="obj"></param>
  66. /// <returns></returns>
  67. public static string GetFieldValue<T>(T t,string FieldName) where T : class
  68. {
  69. try
  70. {
  71. Type Ts = t.GetType();
  72. object o = Ts.GetProperty(FieldName).GetValue(t, null);
  73. string Value = Convert.ToString(o);
  74. if (string.IsNullOrEmpty(Value)) return null;
  75. return Value;
  76. }
  77. catch
  78. {
  79. return null;
  80. }
  81. }
  82. }
  83. }