ReflectTest.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*-------------------------------------------------------------------------
  2. * 功能描述:ReflectTest
  3. * 作者:xulisong
  4. * 创建时间: 2019/3/12 15:05:10
  5. * 版本号:v1.0
  6. * -------------------------------------------------------------------------*/
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using FWindSoft.Tools;
  14. namespace Test.CalcTrans
  15. {
  16. public static class ReflectTest
  17. {
  18. public static T Create<T>(Dictionary<string,string> dic)
  19. {
  20. T t = Activator.CreateInstance<T>();
  21. PropertyInfo[] properties = t.GetType().GetProperties();
  22. for (int i = 0; i < properties.Length; i++)
  23. {
  24. PropertyInfo propertyInfo = properties[i];
  25. try
  26. {
  27. var value = dic[propertyInfo.Name];
  28. propertyInfo.SetValue(t, TypeUtil.ChangeType(value, propertyInfo.PropertyType) ?? "", null);
  29. }
  30. catch(Exception ex)
  31. {
  32. }
  33. }
  34. return t;
  35. }
  36. public static void Test()
  37. {
  38. Dictionary<string, string> value = new Dictionary<string, string>();
  39. value["IntValue"] = "15";
  40. value["BoolValue"] = "true";
  41. value["StringValue"] = "13";
  42. value["DoubleValue"] = "15.18";
  43. value["EnumValue"] = "Hello";
  44. var item = Create<ReflectItem>(value);
  45. }
  46. }
  47. public class ReflectItem
  48. {
  49. public int IntValue { get; set; }
  50. public bool BoolValue { get; set; }
  51. public string StringValue { get; set; }
  52. public double DoubleValue { get; set; }
  53. public ReflectEnum EnumValue { get; set; }
  54. }
  55. public enum ReflectEnum
  56. {
  57. None,
  58. Hello,
  59. }
  60. }