示例#1
0
        private Expression ParseElementAccess(Expression expr)
        {
            int errorPos = Token.Position;

            if (Token.Text[0] != '[')
            {
                throw Error.ParseError(Token, Res.OpenBracketExpected);
            }

            NextToken();
            Expression[] args;
            if (this.Token.Is(TokenId.Identifier))
            {
                args = new[] { Expression.Constant(Token.Text) };
                NextToken();
            }
            else
            {
                args = ParseArguments();
            }

            Token.Validate(TokenId.CloseBracket, Res.CloseBracketOrCommaExpected);
            NextToken();
            if (expr.Type.IsArray)
            {
                if (expr.Type.GetArrayRank() != 1 || args.Length != 1)
                {
                    throw Error.ParseError(errorPos, Res.CannotIndexMultiDimArray);
                }
                Expression index = ExpressionUtility.PromoteExpression(args[0], typeof(int), true);
                if (index == null)
                {
                    throw Error.ParseError(errorPos, Res.InvalidIndex);
                }
                return(Expression.ArrayIndex(expr, index));
            }
            else
            {
                MethodBase mb;
                switch (TypeUtility.FindIndexer(expr.Type, args, out mb))
                {
                case 0:
                    throw Error.ParseError(errorPos, Res.NoApplicableIndexer,
                                           TypeUtility.GetTypeName(expr.Type));

                case 1:
                    return(Expression.Call(expr, (MethodInfo)mb, args));

                default:
                    throw Error.ParseError(errorPos, Res.AmbiguousIndexerInvocation,
                                           TypeUtility.GetTypeName(expr.Type));
                }
            }
        }