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

问题描述 投票:2回答:2

如何通过c#表达式模拟字符串+字符串表达式。 Expression.Add方法不起作用。

字符串+字符串表达式

"111" + "222" = "111222"

谢谢

c# expression
2个回答
3
投票

你需要调用string.Concat(C#编译器将字符串连接转换为对string.Concat的调用)。

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;

并在调试器中检查它,你会看到它生成一个BinaryExpressionMethodstring.Concat(string, string)),而不是MethodCallExpression。因此编译器实际上使用@kalimag的答案,而不是我的答案。然而,两者都有效。


2
投票

Expression.Add有一个带有MethodInfo的重载,它可以是任何与给定参数类型兼容的static方法:

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

在实践中,这与Expression.Call类似,但它会生成不同的表达式树,并在调试器中以不同方式显示。

© www.soinside.com 2019 - 2024. All rights reserved.