Expression for string

How can I get a string like

Namespace.IMyService.Do("1")

from the expression shown in this snippet:

IMyService myService = ...;
int param1 = 1;

myExpressionService.Get(c => myService.Do(param1));

Actually I do not want to call Doif the condition is not satisfied using the created string.

+3
source share
3 answers

You need to get through Expression trees. Here is a sample code:

internal static class myExpressionService
{
    public static string Get(Expression<Action> expression)
    {
        MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
        var method = methodCallExpression.Method;
        var argument = (ConstantExpression) methodCallExpression.Arguments.First();

        return string.Format("{0}.{1}({2})", method.DeclaringType.FullName, method.Name, argument.Value);
    }
}

It works if called this way: string result = myExpressionService.Get(() => myService.Do(1));

Output: Namespace.IMyService.Do(1)

You can extend / update it to process your script.

+4
source

This will also work (although this is not particularly elegant):

public static string MethodCallExpressionRepresentation(this LambdaExpression expr)
{
    var expression = (MethodCallExpression)expr.Body;

    var arguments = string.Join(", ", expression.Arguments.OfType<MemberExpression>().Select(x => {
        var tempInstance = ((ConstantExpression)x.Expression).Value;
        var fieldInfo = (FieldInfo)x.Member;
        return "\"" + fieldInfo.GetValue(tempInstance).ToString() + "\"";
    }).ToArray());

    return expression.Object.Type.FullName + "." + expression.Method.Name + "(" + arguments + ")";
}

You can call it like this:

Expression<Action> expr = c => myService.Do(param1));
var repr = expr.MethodCallExpressionRepresentation();    // Namespace.IMyService.Do("1")
+1
source

.ToString() . MS ToString() . ?

0

All Articles