繁体   English   中英

生成一个 C# 表达式,可以将两个字符串连接在一起

[英]Generate a C# expression that can concatenate two strings together

我试图在动态 linq 表达式中将两个字符串连接在一起。 我传递给 function 的参数必须是Dictionary<string, object> 问题是 The Expression.Add 向我抛出一个错误,因为它不知道如何添加字符串。

我想要达到的目标:

x => (string)x["FirstName"] + " Something here..."

我拥有的:

var pe = Expression.Parameter(typeof(Dictionary<string, object>), "x");
var firstName = Expression.Call(pe, typeof(Dictionary<string, object>).GetMethod("get_Item"), Expression.Constant("FirstName"));
var prop = Expression.Convert(firstName, typeof(string));
var exp = Expression.Add(prop, Expression.Constant(" Something here..."))

添加字符串既不是表达式显式处理的类型之一(就像它对数字基元所做的那样),也不会由于+的重载而起作用(因为string没有这样的重载),因此您需要显式定义应该是的方法重载时调用:

Expression.Add(
  prop,
  Expression.Constant(" Something here..."),
  typeof(string).GetMethod("Concat", new []{typeof(string), typeof(string)}))

这使得使用两个字符串参数的string.Concat的重载成为使用的方法。

您也可以使用Expresssion.Call但这会使您的+意图明确(因此,这是 C# 编译器在生成表达式时所做的事情)。

添加和连接是完全不同的过程。 当您将两个字符串“添加”在一起时,您将它们连接起来,因为对字符串进行数学加法是没有意义的。

连接字符串的最佳方法是使用String.Concat 您可以使用Expression.Call生成方法表达式:

// Create the parameter expressions
var strA = Expression.Parameter(typeof(string));
var strB = Expression.Parameter(typeof(string));

// Create a method expression for String.Join
var methodInfo = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
var join = Expression.Call(methodInfo, strA, strB);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM