问题描述
如何通过c#表达式模拟字符串+字符串表达式. Expression.Add方法不起作用.
How can I simulate string + string expression via c# expression. The Expression.Add method does not work.
字符串+字符串表达式
"111" +"222" ="111222"
"111" + "222" = "111222"
谢谢
推荐答案
您需要调用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.
这篇关于如何通过表达式模拟字符串+字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!