LINQ 表达式转换/从 Int 到字符串的 Concat [英] LINQ Expression Conversion / Concat from Int to string

查看:30
本文介绍了LINQ 表达式转换/从 Int 到字符串的 Concat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想连接两个表达式作为最终表达式

I want to Concat two expressions for the final expression

Expression<Func<T, string>>

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

So I have created expression belwo code works fine for only string types , If I get memberExpression as Int32 or DateTime throwing exception

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

Expression of type 'System.Int32' cannot be used for parameter of type 'System.String' of method 'System.String Concat(System.String, System.String)'

如果我将表达式转换为

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

getting 在类型System.Int32"和System.String"之间没有定义强制运算符.

getting No coercion operator is defined between types 'System.Int32' and '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(),而不是尝试转换为字符串:

Instead of trying to cast to string, you could try casting to object then calling ToString(), as though you were doing:

var converted = member.ToString();

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

As an Expression, it will look something like this:

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

这篇关于LINQ 表达式转换/从 Int 到字符串的 Concat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆