C# LINQ表达式从Int到字符串的转换/Concat

C# LINQ表达式从Int到字符串的转换/Concat,c#,asp.net,linq,c#-4.0,asp.net-mvc-4,C#,Asp.net,Linq,C# 4.0,Asp.net Mvc 4,我想用两个表达式来表示最后的表达式 Expression<Func<T, string>> 在类型“System.Int32”和“System.String”之间定义了不获取强制运算符 请帮我解决这个问题 代码 MethodInfo bodyContactMethod = typeof (string).GetMethod("Concat",new[] {typeof (string), typeof (string)}); ParameterExpression p

我想用两个表达式来表示最后的表达式

Expression<Func<T, 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<T, string>>(body, parameter);
MethodInfo bodyContactMethod=typeof(string).GetMethod(“Concat”,new[]{typeof(string),typeof(string)});
ParameterExpression参数=Expression.parameter(typeof(T));
body=Expression.Call(bodyContactMethod、cons、memberExpression);
返回表达式.Lambda(主体,参数);

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

var converted = member.ToString();
作为一个表达式,它将如下所示:

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

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


尽管有点晚了,但我还是要继续阐述理查德·迪明的答案

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

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

它可以进一步简化为:

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

为什么不更改您的方法签名以获取一个“object”,然后对everything.ExpressionHi,我在GroupBy中使用这个表达式,所以我需要上面的格式,当我在LINQ Group By中使用这个表达式时,让concat不使用object,object类型
Expression.Call(
    typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }),
    Expression.Convert(cons, typeof(object)),
    Expression.Convert(memberExpression, typeof(object))
);
var convertedExpression = Expression.Call(
                     memberExpression,
                     typeof(object).GetMethod("ToString"));