Skip to content

Commit ba408ea

Browse files
committed
Correctly translating static method conversion expressions - fixes issue #20
1 parent a33e857 commit ba408ea

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

ReadableExpressions.UnitTests/WhenTranslatingConversions.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
{
33
using System;
44
using System.IO;
5+
using NetStandardPolyfills;
56
#if !NET35
67
using System.Linq.Expressions;
78
using Xunit;
@@ -86,5 +87,24 @@ public void ShouldTranslateAnUnboxExpression()
8687

8788
translated.ShouldBe("((int)o)");
8889
}
90+
91+
// https://github.com/agileobjects/ReadableExpressions/issues/20
92+
[Fact]
93+
public void ShouldTranslateConversionWithCustomStaticMethod()
94+
{
95+
var stringParameter = Expression.Parameter(typeof(string), "str");
96+
var targetType = typeof(int);
97+
98+
var body = Expression.Convert(
99+
stringParameter,
100+
targetType,
101+
targetType.GetPublicStaticMethod(nameof(int.Parse), stringParameter.Type));
102+
103+
var stringToIntParseLambda = Expression.Lambda<Func<string, int>>(body, stringParameter);
104+
105+
var translated = ToReadableString(stringToIntParseLambda.Body);
106+
107+
translated.ShouldBe("int.Parse(str)");
108+
}
89109
}
90110
}

ReadableExpressions/Translators/CastExpressionTranslator.cs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,13 @@ public string Translate(Expression expression, TranslationContext context)
3636

3737
private static string TranslateCast(Expression expression, TranslationContext context)
3838
{
39-
var operand = ((UnaryExpression)expression).Operand;
39+
var cast = (UnaryExpression)expression;
40+
var operand = cast.Operand;
41+
42+
if ((cast.Method != null) && !cast.Method.IsExplicitOperator() && !cast.Method.IsImplicitOperator())
43+
{
44+
return TranslateMethodConversion(cast, context);
45+
}
4046

4147
if (expression.Type == typeof(object))
4248
{
@@ -67,6 +73,16 @@ private static string TranslateCast(Expression expression, TranslationContext co
6773
return TranslateCastCore(expression, context);
6874
}
6975

76+
private static string TranslateMethodConversion(UnaryExpression cast, TranslationContext context)
77+
{
78+
return MethodCallExpressionTranslator.GetMethodCall(
79+
cast.Method.DeclaringType.GetFriendlyName(),
80+
new BclMethodInfoWrapper(cast.Method),
81+
new[] { cast.Operand },
82+
cast,
83+
context);
84+
}
85+
7086
private static string TranslateCastCore(Expression expression, TranslationContext context)
7187
{
7288
var cast = (UnaryExpression)expression;

0 commit comments

Comments
 (0)