我想连接两个表达式作为最终表达式
Expression<Func<T, string>>
所以我创建的表达式 belwo 代码仅适用于字符串类型,如果我将 memberExpression 作为 Int32 或 DateTime 抛出异常
“System.Int32”类型的表达式不能用于方法“System.String Concat(System.String, System.String)”的“System.String”类型的参数
如果我将表达式转换为
var conversion = Expression.Convert(memberExpression, typeof (string));
getting No coercion operator is defined between types 'System.Int32' and 'System.String'.
请帮我解决
代码
MethodInfo bodyContactMethod = typeof (string).GetMethod("Concat",new[] {typeof (string), typeof (string)});
ParameterExpression parameter = Expression.Parameter(typeof (T));
body = Expression.Call(bodyContactMethod, cons, memberExpression);
return Expression.Lambda<Func<T, string>>(body, parameter);
最佳答案
您可以尝试转换为对象然后调用 ToString(),而不是尝试转换为字符串,就像您正在做的那样:
var converted = member.ToString();
作为表达式,它看起来像这样:
var convertedExpression = Expression.Call(
Expression.Convert(memberExpression, typeof(object)),
typeof(object).GetMethod("ToString"));
关于c# - 从 Int 到字符串的 LINQ 表达式转换/连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17862314/