如何通过表达式模拟字符串+字符串? [英] How to simulate string + string via expression?

查看:80
本文介绍了如何通过表达式模拟字符串+字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过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(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.

这篇关于如何通过表达式模拟字符串+字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆