我正在尝试在动态linq表达式中将两个字符串连接在一起。传递给函数的参数必须是Dictionary<string, object>
。问题是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..."))
答案 0 :(得分:3)
添加字符串既不是表达式明确处理的类型之一(就像数字基元一样),也不会因+
的重载而起作用(因为string
没有这样的重载),所以你需要明确定义重载时应该调用的方法:
Expression.Add(
prop,
Expression.Constant(" Something here...")
typeof(string).GetMethod("Concat", new []{typeof(string), typeof(string)}))
这使得string.Concat
的重载使用了两个字符串参数。
您也可以使用Expresssion.Call
但这会使您的+
意图明确(并且是C#编译器在生成表达式时所执行的操作)。
答案 1 :(得分:0)
添加和连接是完全不同的过程。当你&#34;添加&#34;两个字符串在一起,你是连接它们,因为对字符串进行数学加法是没有意义的。
连接字符串的最佳方法是使用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);