c# – 从Int到string的LINQ表达式转换/ Concat
发布时间:2020-12-15 08:42:57 所属栏目:百科 来源:网络整理
导读:我想将Concat的两个表达式用于最终表达式 ExpressionFuncT,string 所以我创建了表达式belwo代码只适用于字符串类型,如果我将memberExpression作为Int32或DateTime抛出异常 类型’System.Int32’的表达式不能用于方法’System.String Concat(System.String,Sy
我想将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")); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |