问题
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