Skip to content

Commit 90becd7

Browse files
committed
use Enum.Parse<TEnum>
1 parent b8f8546 commit 90becd7

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

src/AutoMapper/Mappers/StringToEnumMapper.cs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ namespace AutoMapper.Internal.Mappers
99
using static Expression;
1010
public class StringToEnumMapper : IObjectMapper
1111
{
12-
private static readonly MethodInfo EqualsMethod = typeof(StringToEnumMapper).GetMethod("StringCompareOrdinalIgnoreCase");
13-
private static readonly MethodInfo ParseMethod = typeof(Enum).GetMethod("Parse", new[] { typeof(Type), typeof(string), typeof(bool) });
14-
private static readonly MethodInfo IsNullOrEmptyMethod = typeof(string).GetMethod("IsNullOrEmpty");
12+
private static readonly MethodInfo EqualsMethod = typeof(StringToEnumMapper).GetMethod(nameof(StringCompareOrdinalIgnoreCase));
13+
private static readonly MethodInfo ParseMethod = typeof(Enum).StaticGenericMethod("Parse", parametersCount: 2);
14+
private static readonly PropertyInfo LengthProperty = typeof(string).GetProperty("Length");
1515
public bool IsMatch(TypePair context) => context.SourceType == typeof(string) && context.DestinationType.IsEnum;
1616
public Expression MapExpression(IGlobalConfiguration configurationProvider, ProfileMap profileMap,
1717
MemberMap memberMap, Expression sourceExpression, Expression destExpression)
@@ -29,9 +29,10 @@ public Expression MapExpression(IGlobalConfiguration configurationProvider, Prof
2929
switchCases.Add(switchCase);
3030
}
3131
}
32-
var enumParse = ToType(Call(ParseMethod, Constant(destinationType), sourceExpression, True), destinationType);
32+
var ignoreCase = True;
33+
Expression enumParse = Call(ParseMethod.MakeGenericMethod(destinationType), sourceExpression, ignoreCase);
3334
var parse = switchCases != null ? Switch(sourceExpression, enumParse, EqualsMethod, switchCases) : enumParse;
34-
return Condition(Call(IsNullOrEmptyMethod, sourceExpression), Default(destinationType), parse);
35+
return Condition(Equal(Property(sourceExpression, LengthProperty), Zero), Default(destinationType), parse);
3536
}
3637
public static bool StringCompareOrdinalIgnoreCase(string x, string y) => StringComparer.OrdinalIgnoreCase.Equals(x, y);
3738
}

0 commit comments

Comments
 (0)