LINQ表达式转换/从Int到String的Concat

我想用Concat两个表达式作为最终表达式

Expression<Func> 

所以我创建了表达式belwo代码只适用于字符串类型,如果我将memberExpression作为Int32或DateTime抛出exception

类型’System.Int32’的表达式不能用于方法’System.String Concat(System.String,System.String)’的’System.String’类型的参数

如果我将表达式转换为

 var conversion = Expression.Convert(memberExpression, typeof (string)); 

获取没有强制运算符是在类型’System.Int32’和’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>(body, parameter); 

您可以尝试转换为对象然后调用ToString(),而不是尝试强制转换为字符串,就好像您正在执行的操作:

 var converted = member.ToString(); 

作为表达式,它看起来像这样:

 var convertedExpression = Expression.Call( Expression.Convert(memberExpression, typeof(object)), typeof(object).GetMethod("ToString")); 

您可以尝试调用string.Concat(object, object) string.Concat(string, string)而不是调用string.Concat(string, string) string.Concat(object, object)

 MethodInfo bodyContactMethod = typeof (string).GetMethod("Concat", new[] { typeof(object), typeof(object) }); 

为了扩展Richard Deeming的答案,即使它有点晚了。

 Expression.Call( typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }), Expression.Convert(cons, typeof(object)), Expression.Convert(memberExpression, typeof(object)) ); 

这应该工作得很好,同时允许签名保持原样。