LINQ防爆pression转换/的毗连从int到字符串 [英] LINQ Expression Conversion / Concat from Int to string

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

问题描述

我想CONCAT为最后的前pression两位前pressions

 防爆pression<&Func键LT; T,串>>

所以,我创建了前pression belwo code只有字符串类型工作得很好,如果我memberEx pression如的Int32或日期时间抛出异常

实施例$类型'System.Int32'的对$ pssion不能用于类型方法'System.String的毗连(System.String,System.String)'

的'System.String'的参数

如果我转换前pression为

  VAR转换=前pression.Convert(memberEx pression的typeof(字符串));

没有得到强制经营者类型'System.Int32'和'System.String'之间。

请帮我解决。

code

  MethodInfo的bodyContactMethod = typeof运算(字符串).GetMethod(的毗连,新的[] {typeof运算(字符串),typeof运算(字符串)});ParameterEx pression参数=前pression.Parameter(typeof运算(T));机身前= pression.Call(bodyContactMethod,利弊,memberEx pression);返回前pression.Lambda<&Func键LT; T,串>>(机身,参数);


解决方案

而不是试图转换为字符串,你可以尝试转换为对象,然后调用toString()方法,就好像你在做:

  VAR转换= member.ToString();

作为Ex pression,它看起来是这样的:

  VAR convertedEx pression =前pression.Call(
                     防爆pression.Convert(memberEx pression的typeof(对象)),
                     typeof运算(对象).GetMethod(的ToString));

I want to Concat two expressions for the final expression

Expression<Func<T, string>>

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

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

If I convert the expression as

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

getting No coercion operator is defined between types 'System.Int32' and 'System.String'.

Please help me to resolve

Code

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);

解决方案

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防爆pression转换/的毗连从int到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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