I want to capture a method call as an expression, but evaluate its arguments in a type-safe and IDE-friendly way beforehand.
Take the following example class:
class Test
{
public string SomeMethod(int a, string b) { ... }
}
I now want to pass a call to SomeMethod
to a function receiving an Expression
:
HandleMethodCall<Test>(test => test.SomeMethod("string".Length, 5.ToString()));
Right now HandleMethodCall
has the signature
static void HandleMethodCall<T>(Expression<Func<T, object>> expr)
Unfortunately, in this case the expression passed to HandleMethodCall
does not only contain test.SomeMethod()
, but expression trees for the arguments as well.
A workaround would be to split the method call and its arguments into different arguments for HandleMethodCall
, but this has the cost of losing compile-time type-safety and IDE support for showing argument names.
Is there any way to make the compiler evaluate parts of an expression before putting them into an Expression
object?
Or, alternatively, is it possible to manually invoke evaluation of the expression trees for the method parameters?