What if you nested the MemberExpressionVisitor
class inside another class? Since I like extension methods, create a static class that contains an extension method on Expression<Func<T,TRes>>
that creates the visitor, runs it and returns the result:
static class LambdaExt {
public static List<string> GetAccessedMemberNames<T, TRes>(this Expression<Func<T, TRes>> startExpr) {
var v = new MemberExpressionVisitor<T, TRes>();
v.Visit(startExpr);
return v.GetAccessedMembers();
}
// put MemberExpressionVisitor definition here
}
Now you can use it like:
Console.WriteLine(String.Join(", ", exp.GetAccessedMemberNames()));
Alternatively, you can add a constructor to MemberExpressionVisitor
:
public MemberExpressionVisitor(Expression<Func<T1, T2>> startExpression) {
originalExpression = startExpression;
Visit(startExpression);
}
remove the Visit
override entirely, and simplify the extension method to:
public static List<string> GetAccessedMemberNames<T, TRes>(this Expression<Func<T, TRes>> startExpr) =>
new MemberExpressionVisitor<T,TRes>(startExpr).GetAccessedMembers();
This has the compiler enforce type safety, assuming you know your lambda expression variables types properly.