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

ine*_*e p 7 c# linq asp.net c#-4.0 asp.net-mvc-4

我想将Concat的两个表达式用于最终表达式

Expression<Func<T, string>>
Run Code Online (Sandbox Code Playgroud)

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

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

如果我将表达式转换为

var conversion = Expression.Convert(memberExpression, typeof (string));
Run Code Online (Sandbox Code Playgroud)

获取没有强制运算符是在类型'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<T, string>>(body, parameter);
Run Code Online (Sandbox Code Playgroud)

Jon*_*n G 9

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

var converted = member.ToString();
Run Code Online (Sandbox Code Playgroud)

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

var convertedExpression = Expression.Call(
                     Expression.Convert(memberExpression, typeof(object)),
                     typeof(object).GetMethod("ToString"));
Run Code Online (Sandbox Code Playgroud)