ReflectionMapper.cs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ShwasherSys.ReflectionMagic
  7. {
  8. public class ReflectionMapper<TIn,TOut>
  9. {
  10. /// <summary>
  11. ///
  12. /// </summary>
  13. /// <typeparam name="TIn"></typeparam>
  14. /// <typeparam name="TOut"></typeparam>
  15. /// <param name="tIn"></param>
  16. /// <returns></returns>
  17. public static TOut Trans<TIn, TOut>(TIn tIn)
  18. {
  19. TOut tout = Activator.CreateInstance<TOut>();
  20. foreach (var itemOut in tout.GetType().GetProperties())
  21. {
  22. var propIn = tIn.GetType().GetProperty(itemOut.Name);
  23. itemOut.SetValue(tout,propIn?.GetValue(tIn));
  24. }
  25. foreach (var itemOut in tout.GetType().GetFields())
  26. {
  27. var fieldIn = tIn.GetType().GetField(itemOut.Name);
  28. itemOut.SetValue(tout, fieldIn?.GetValue(tIn));
  29. }
  30. return tout;
  31. }
  32. }
  33. }