And*_*eta 2 c# linq lambda asp.net-core
我试图在动态 linq 表达式中将两个字符串连接在一起。我传递给函数的参数必须是Dictionary<string, object>. 问题是 Expression.Add 向我抛出了一个错误,因为它不知道如何添加字符串。
我正在努力实现的目标:
x => (string)x["FirstName"] + " Something here..."
Run Code Online (Sandbox Code Playgroud)
我拥有的:
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..."))
Run Code Online (Sandbox Code Playgroud)
添加字符串既不是表达式显式处理的类型之一(就像它对数字基元所做的那样),也不是由于重载+(因为string没有这样的重载)而起作用,因此您需要显式定义应该在以下情况下调用的方法重载:
Expression.Add(
prop,
Expression.Constant(" Something here...")
typeof(string).GetMethod("Concat", new []{typeof(string), typeof(string)}))
Run Code Online (Sandbox Code Playgroud)
这使得该方法的重载string.Concat需要两个字符串参数。
您也可以使用,Expresssion.Call但这会使您的+意图明确(出于这个原因,这也是 C# 编译器在生成表达式时所做的)。
| 归档时间: |
|
| 查看次数: |
2388 次 |
| 最近记录: |