c# - 字符串表达式

标签 c# expression expression-trees

我怎样才能得到像这样的字符串

Namespace.IMyService.Do("1")

从此片段中演示的表达式:

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

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

我实际上不想调用 Do 除非使用生成的字符串满足条件。

最佳答案

您将不得不遍历表达式树。这是一些示例代码:

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);
    }
}

如果以这种方式调用它会起作用:string result = myExpressionService.Get(() => myService.Do(1));

输出是:Namespace.IMyService.Do(1)

您可以扩展/更新它来处理您的场景。

关于c# - 字符串表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5384361/

相关文章:

c# - 将表达式转换为另一个表达式?

if-statement - 嵌套 If 语句 SSRS 表达式

java - Xpath Java 通过测试值获取元素

c# - 我该如何清理这个 lambda?

c# - 如何在 lambda 表达式参数中扩展谓词

c# - 何时不使用 RegexOptions.Compiled

c# - 从字典中获取第一个元素

c# - 将十六进制颜色转换为整数

c# - 如何同时触发客户端和 MVC 验证?

c# - PredicateBuilder 方法说明