9using System.Linq.Expressions;
10using System.Reflection;
19 public static class Reflect<TTarget>
26 public static System.Reflection.MethodInfo GetMethod(Expression<Action<TTarget>> method)
28 return GetMethodInfo(method);
36 public static System.Reflection.MethodInfo GetMethod<T1>(Expression<Action<TTarget, T1>> method)
38 return GetMethodInfo(method);
46 public static System.Reflection.MethodInfo GetMethod<T1, T2>(Expression<Action<TTarget, T1, T2>> method)
48 return GetMethodInfo(method);
56 public static System.Reflection.MethodInfo GetMethod<T1, T2, T3>(Expression<Action<TTarget, T1, T2, T3>> method)
58 return GetMethodInfo(method);
61 private static System.Reflection.MethodInfo GetMethodInfo(Expression method)
63 if (method ==
null)
throw new ArgumentNullException(
"method");
65 var lambda = method as LambdaExpression;
66 if (lambda ==
null)
throw new ArgumentException(
"Not a lambda expression",
"method");
67 if (lambda.Body.NodeType != ExpressionType.Call)
throw new ArgumentException(
"Not a method call",
"method");
69 return ((MethodCallExpression)lambda.Body).Method;
77 public static PropertyInfo GetProperty(Expression<Func<TTarget, object>> property)
79 var info = GetMemberInfo(property) as PropertyInfo;
80 if (info ==
null)
throw new ArgumentException(
"Member is not a property");
93 public static PropertyInfo GetProperty<P>(Expression<Func<TTarget, P>> property)
95 var info = GetMemberInfo(property) as PropertyInfo;
96 if (info ==
null)
throw new ArgumentException(
"Member is not a property");
106 public static FieldInfo GetField(Expression<Func<TTarget, object>> field)
108 var info = GetMemberInfo(field) as FieldInfo;
109 if (info ==
null)
throw new ArgumentException(
"Member is not a field");
114 private static MemberInfo GetMemberInfo(Expression member)
116 if (member ==
null)
throw new ArgumentNullException(
"member");
118 var lambda = member as LambdaExpression;
119 if (lambda ==
null)
throw new ArgumentException(
"Not a lambda expression",
"member");
121 MemberExpression memberExpr =
null;
125 if (lambda.Body.NodeType == ExpressionType.Convert)
129 memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
131 else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
133 memberExpr = lambda.Body as MemberExpression;
136 if (memberExpr ==
null)
throw new ArgumentException(
"Not a member access",
"member");
138 return memberExpr.Member;