Extensions.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Linq.Expressions;
  3. using System.Reflection;
  4. namespace DymWebForm.Common.Reflection
  5. {
  6. internal static class Extensions
  7. {
  8. public static Func<object, object> GenerateGetterFunc(this PropertyInfo pi)
  9. {
  10. //p=> ((pi.DeclaringType)p).<pi>
  11. var expParamPo = Expression.Parameter(typeof(object), "p");
  12. var expParamPc = Expression.Convert(expParamPo, pi.DeclaringType);
  13. var expMma = Expression.MakeMemberAccess(
  14. expParamPc
  15. , pi
  16. );
  17. var expMmac = Expression.Convert(expMma, typeof(object));
  18. var exp = Expression.Lambda<Func<object, object>>(expMmac, expParamPo);
  19. return exp.Compile();
  20. }
  21. public static Action<object, object> GenerateSetterAction(this PropertyInfo pi)
  22. {
  23. //p=> ((pi.DeclaringType)p).<pi>=(pi.PropertyType)v
  24. var expParamPo = Expression.Parameter(typeof(object), "p");
  25. var expParamPc = Expression.Convert(expParamPo, pi.DeclaringType);
  26. var expParamV = Expression.Parameter(typeof(object), "v");
  27. var expParamVc = Expression.Convert(expParamV, pi.PropertyType);
  28. var expMma = Expression.Call(
  29. expParamPc
  30. , pi.GetSetMethod()
  31. , expParamVc
  32. );
  33. var exp = Expression.Lambda<Action<object, object>>(expMma, expParamPo, expParamV);
  34. return exp.Compile();
  35. }
  36. }
  37. }