示例#1
0
        public static Expression Unwrap(Expression expr)
        {
            var visitor = new ConditionUnwrapper();
            var result  = visitor.Visit(expr);

            return(result);
        }
示例#2
0
        protected Expression CatchNullReference(MethodCallExpression expr)
        {
            if (expr.Object == null)
            {
                return(expr);
            }

            if (!expr.Object.Type.IsValueType || expr.Object.Type.IsNullable())
            {
                var @null     = Expression.Constant(null, expr.Object.Type);
                var isNull    = Expression.Equal(@null, expr.Object);
                var exception = Expression.Constant(new NullReferenceException($"Object reference not set to an instance of an object calling method '{expr.Method.Name}' in expression '{ConditionUnwrapper.Unwrap(expr)}'. Consider using a ternary expression to specify conditional access."));
                var @throw    = Expression.Throw(exception);
                var block     = Expression.Block(@throw, Expression.Default(expr.Type));
                var condition = Expression.Condition(isNull, block, expr);

                return(condition);
            }
            else
            {
                return(expr);
            }
        }