“没有为类型’System.String’和’System.String’定义二元运算符Add。” – 真的吗?

尝试运行以下代码时:

Expression<Func> stringExpression = Expression.Lambda<Func>( Expression.Add( stringParam, Expression.Constant("A") ), new List() { stringParam } ); string AB = stringExpression.Compile()("B"); 

我得到标题中引用的错误:“没有为类型’System.String’和’System.String’定义二进制运算符Add。” 那是真的吗? 显然在C#中它起作用。 表达式编译器无法访问C#特殊语法糖中的string s = "A" + "B"吗?

这是绝对正确的,是的。 没有这样的运算符string.Concat #编译器将string + string转换为对string.Concat的调用。 (这很重要,因为它意味着x + y + z可以转换为string.Concat(x, y, z) ,这避免了无意义地创建中间字符串。

查看字符串运算符的文档 – 只有==!=由框架定义。

是的,这是一个惊喜不是它! 编译器将其替换为对String.Concat的调用。

这也引起了我的注意,正如Jon在回答中指出的那样,C#编译器将string + string转换为string.Concat 。 Expression.Add方法存在重载 ,允许您指定要使用的“添加”方法。

 var concatMethod = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) }); var addExpr = Expression.Add(Expression.Constant("hello "),Expression.Constant("world"), concatMethod); 

您可能希望更改string.Concat方法以使用正确的重载 。

certificate这是有效的:

 Console.WriteLine(Expression.Lambda>(addExpr).Compile()()); 

将输出:

你好,世界