/ Published in: C#
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
public static void RenderProperty(Person person, Expression<Func<Person, object>> expression) { Func<Person, object> function = expression.Compile(); object o = function(person); var memberExpression = GetMemberExpression(expression); var propertyType = GetTypeFromMemberExpression(memberExpression); var declaringType = memberExpression == null ? null : memberExpression.Expression.Type; var inferredName = memberExpression == null ? null : memberExpression.Member.Name; } public static MemberExpression GetMemberExpression(LambdaExpression expression) { return RemoveUnary(expression.Body) as MemberExpression; } private static Expression RemoveUnary(Expression body) { var unary = body as UnaryExpression; if (unary != null) return unary.Operand; return body; } private static Type GetTypeFromMemberExpression(MemberExpression memberExpression) { if (memberExpression == null) return null; var dataType = GetTypeFromMemberInfo(memberExpression.Member, (PropertyInfo p) => p.PropertyType); if (dataType == null) dataType = GetTypeFromMemberInfo(memberExpression.Member, (MethodInfo m) => m.ReturnType); if (dataType == null) dataType = GetTypeFromMemberInfo(memberExpression.Member, (FieldInfo f) => f.FieldType); return dataType; } private static Type GetTypeFromMemberInfo<TMember>(MemberInfo member, Func<TMember, Type> func) where TMember : MemberInfo { return func((TMember) member); return null; }