如何通过c#表达式模拟字符串+字符串表达式。 Expression.Add方法不起作用。
字符串+字符串表达式
"111" + "222" = "111222"
谢谢
你需要调用string.Concat
(C#编译器将字符串连接转换为对string.Concat
的调用)。
var concatMethod = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
var first = Expression.Constant("a");
var second = Expression.Constant("b");
var concat = Expression.Call(concatMethod, first, second);
var lambda = Expression.Lambda<Func<string>>(concat).Compile();
Console.WriteLine(lambda()); // "ab"
实际上,如果你写
Expression<Func<string, string string>> x = (a, b) => a + b;
并在调试器中检查它,你会看到它生成一个BinaryExpression
(Method
的string.Concat(string, string)
),而不是MethodCallExpression
。因此编译器实际上使用@kalimag的答案,而不是我的答案。然而,两者都有效。
Expression.Add
有一个带有MethodInfo
的重载,它可以是任何与给定参数类型兼容的static
方法:
var concatMethod = typeof(string).GetMethod(nameof(String.Concat), new [] { typeof(string), typeof(string)});
var expr = Expression.Add(Expression.Constant("a"), Expression.Constant("b"), concatMethod);
在实践中,这与Expression.Call
类似,但它会生成不同的表达式树,并在调试器中以不同方式显示。