LINQ Expression Conversion / Concat from Int to String

I want to execute two expressions for the final expression

Expression<Func<T, string>> 

So, I created the expression belwo code works fine only for string types. If I get a MemberExpression expression as an Int32 or DateTime throw exception

An expression of type "System.Int32" cannot be used for a parameter of type "System.String" of the method "System.String Concat (System.String, System.String)"

If I transform the expression as

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

The receipt of a coercion statement is not defined between the types System.Int32 and System.String.

Please help me decide

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); 
+7
source share
4 answers

Instead of trying to pass to a string, you can try casting the object and then calling ToString (), as if 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")); 
+7
source

This can be further simplified to:

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

Instead of calling string.Concat(string, string) you can try calling string.Concat(object, object) :

 MethodInfo bodyContactMethod = typeof (string).GetMethod("Concat", new[] { typeof(object), typeof(object) }); 
0
source

Expand Richard Deming's answer, although he was a little late.

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

This should work fine, allowing the signature to remain as it is.

0
source

Source: https://habr.com/ru/post/950280/


All Articles