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

我想将Concat的两个表达式用于最终表达式
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));

获取没有强制运算符是在类型’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);

解决方法

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

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

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

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么