Esempio n. 1
0
        public static bool GetValueFromExpressionWithoutConversion(Expression expression, out object value)
        {
            switch (expression.NodeType)
            {
            case ExpressionType.Constant:
                value = ((ConstantExpression)expression).Value;
                return(true);

            case ExpressionType.MemberAccess:
                value = GetMemberValue(((MemberExpression)expression));
                return(true);

            case ExpressionType.MemberInit:
                var memberInitExpression = ((MemberInitExpression)expression);
                value = Expression.Lambda(memberInitExpression).Compile().DynamicInvoke();
                return(true);

            case ExpressionType.New:
                value = GetNewExpressionValue(expression);
                return(true);

            case ExpressionType.Lambda:
                value = ((LambdaExpression)expression).Compile().DynamicInvoke();
                return(true);

            case ExpressionType.Call:
                value = Expression.Lambda(expression).Compile().DynamicInvoke();
                return(true);

            case ExpressionType.Convert:
                var unaryExpression = ((UnaryExpression)expression);
                if (TypeSystem.IsNullableType(unaryExpression.Type))
                {
                    return(GetValueFromExpressionWithoutConversion(unaryExpression.Operand, out value));
                }
                value = Expression.Lambda(expression).Compile().DynamicInvoke();
                return(true);

            case ExpressionType.NewArrayInit:
                var expressions = ((NewArrayExpression)expression).Expressions;
                var values      = new object[expressions.Count];
                value = null;
                if (expressions.Where((t, i) => !GetValueFromExpressionWithoutConversion(t, out values[i])).Any())
                {
                    return(false);
                }
                value = values;
                return(true);

            case ExpressionType.NewArrayBounds:
                value       = null;
                expressions = ((NewArrayExpression)expression).Expressions;
                var constantExpression = (ConstantExpression)expressions.FirstOrDefault();
                if (constantExpression == null)
                {
                    return(false);
                }
                if (constantExpression.Value.GetType() != typeof(int))
                {
                    return(false);
                }
                var length = (int)constantExpression.Value;
                value = new object[length];
                return(true);

            default:
                value = null;
                return(false);
            }
        }