to string expression

c# expression expression-trees

Question

How can I get a string similar to

Namespace.IMyService.Do("1")

based on the phrase as shown in this clip it:

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

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

Honestly, I don't want to call.Do Unless the created string is used to satisfy a requirement.

1
3
3/21/2011 10:12:38 PM

Accepted Answer

You must go throughExpression trees . Here is a snippet of some 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);
    }
}

If you call it like this:string result = myExpressionService.Get(() => myService.Do(1));

The result is:Namespace.IMyService.Do(1)

To fit your situation, you may add to or alter it.

4
3/21/2011 10:43:29 PM

Popular Answer

Although it's not especially elegant, the following would also function:

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 may refer to it as follows:

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


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow