How to simulate string + string via expression?

戏子无情 提交于 2019-12-24 14:14:16

问题


How can I simulate string + string expression via c# expression. The Expression.Add method does not work.

string + string expression like

"111" + "222" = "111222"

thanks


回答1:


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"

Actually, if you write

Expression<Func<string, string string>> x = (a, b) => a + b;

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.




回答2:


Expression.Add has an overload that takes a MethodInfo, which can be any static method that is compatible with the given parameter types:

var concatMethod = typeof(string).GetMethod(nameof(String.Concat), new [] { typeof(string), typeof(string)});
var expr = Expression.Add(Expression.Constant("a"), Expression.Constant("b"), concatMethod);

In practice this is similar to Expression.Call, but it produces a different expression tree and is displayed differently in the debugger.



来源:https://stackoverflow.com/questions/55182773/how-to-simulate-string-string-via-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!