且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过表达式模拟字符串+字符串?

更新时间: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(Methodstring.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.