Created
February 28, 2021 05:16
-
-
Save leandromoh/a86cfe7b397ca70293eead3b8ee877ea to your computer and use it in GitHub Desktop.
ExpressionVisitor that resolve closures for primitive types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq.Expressions; | |
using System.Reflection; | |
namespace RecordParser.Generic | |
{ | |
public class ClosureVisitor : ExpressionVisitor | |
{ | |
protected override Expression VisitMember(MemberExpression member) | |
{ | |
var isPrimitive = member.Type.IsValueType || member.Type == typeof(string); | |
if (isPrimitive && member.Expression is ConstantExpression constant) | |
{ | |
if (member.Member is FieldInfo fieldInfo) | |
{ | |
var value = fieldInfo.GetValue(constant.Value); | |
return Expression.Constant(value, member.Type); | |
} | |
if (member.Member is PropertyInfo propertyInfo) | |
{ | |
var value = propertyInfo.GetValue(constant.Value); | |
return Expression.Constant(value, member.Type); | |
} | |
} | |
return base.VisitMember(member); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment