Expression as parameter


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public static void RenderProperty(Person person, Expression<Func<Person, object>> expression)
  2. {
  3. Func<Person, object> function = expression.Compile();
  4. object o = function(person);
  5.  
  6. var memberExpression = GetMemberExpression(expression);
  7. var propertyType = GetTypeFromMemberExpression(memberExpression);
  8. var declaringType = memberExpression == null ? null : memberExpression.Expression.Type;
  9. var inferredName = memberExpression == null ? null : memberExpression.Member.Name;
  10. }
  11.  
  12. public static MemberExpression GetMemberExpression(LambdaExpression expression)
  13. {
  14. return RemoveUnary(expression.Body) as MemberExpression;
  15. }
  16.  
  17. private static Expression RemoveUnary(Expression body)
  18. {
  19. var unary = body as UnaryExpression;
  20.  
  21. if (unary != null)
  22. return unary.Operand;
  23.  
  24. return body;
  25. }
  26.  
  27. private static Type GetTypeFromMemberExpression(MemberExpression memberExpression)
  28. {
  29. if (memberExpression == null)
  30. return null;
  31.  
  32. var dataType = GetTypeFromMemberInfo(memberExpression.Member, (PropertyInfo p) => p.PropertyType);
  33.  
  34. if (dataType == null)
  35. dataType = GetTypeFromMemberInfo(memberExpression.Member, (MethodInfo m) => m.ReturnType);
  36.  
  37. if (dataType == null)
  38. dataType = GetTypeFromMemberInfo(memberExpression.Member, (FieldInfo f) => f.FieldType);
  39.  
  40. return dataType;
  41. }
  42.  
  43. private static Type GetTypeFromMemberInfo<TMember>(MemberInfo member, Func<TMember, Type> func) where TMember : MemberInfo
  44. {
  45. if (member is TMember)
  46. return func((TMember) member);
  47.  
  48. return null;
  49. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.