コード例 #1
0
        internal static object GetConstantByExpression(Expression expression)
        {
            ConstantExpressionVisitor constantExpressionVisitor = null;

            if (expression is ConstantExpression)
            {
                constantExpressionVisitor = new ConstantExpressionVisitor();
            }
            else if (expression is MemberExpression)
            {
                constantExpressionVisitor = new MemberConstantExpressionVisitor();
            }
            else if (expression is MethodCallExpression)
            {
                constantExpressionVisitor = new MethodConstantExpressionVisitor();
            }
            else if (expression is ConditionalExpression)
            {
                constantExpressionVisitor = new ConditionalConstantExpressionVisitor();
            }
            else if (expression.GetType().Name == "MethodBinaryExpression")
            {
                constantExpressionVisitor = new MethodBinaryConstantExpressionVisitor();
            }
            else
            {
                throw new Exception($"Unknow expression {expression.GetType()}");
            }
            constantExpressionVisitor.Visit(expression);
            return(constantExpressionVisitor.Value);
        }
        protected override Expression VisitMember(MemberExpression node)
        {
            var visitor = new MemberConstantExpressionVisitor();

            visitor.Visit(node.Expression);
            Type type = visitor.Value.GetType();

            switch (node.Member.MemberType)
            {
            case MemberTypes.Field:
                FieldInfo fieldInfo = type.GetField(node.Member.Name);
                Value = fieldInfo.GetValue(visitor.Value);
                break;

            case MemberTypes.Property:
                PropertyInfo propertyInfo = type.GetProperty(node.Member.Name);
                Value = propertyInfo.GetValue(visitor.Value);
                break;

            default:
                throw new NotSupportedException($"Unknow Member type {node.Member.MemberType}");
            }
            return(node);
        }