更新时间:2023-02-10 20:57:55
您需要调用string.Concat
(C#编译器将字符串连接转换为对string.Concat
的调用).
You need to call into string.Concat
(the C# compiler turns string concatenation into calls to string.Concat
under the hood).
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的答案,而不是我的.两者都可以.
and inspect it in the debugger, you'll see that it generates a BinaryExpression
(with a Method
of string.Concat(string, string)
), not a MethodCallExpression
. Therefore the compiler actually uses @kalimag's answer, and not mine. Both will work, however.