Пример #1
0
        //=========================================================================
        // 分析后读取一个标记
        //=========================================================================
        private Token GetToken()
        {
            Token token = null;

            // 忽略空白字符
            while (HasChar && char.IsWhiteSpace(CurrentChar))
            {
                MoveNext();
            }
            if (!HasChar)
            {
                return(null);
            }
            if (CurrentChar == '(')             // 左括号
            {
                token = new LP();
            }
            else if (CurrentChar == ')')        // 右括号
            {
                token = new RP();
            }
            else if (IsOper(CurrentChar))       // 操作符
            {
                token = new Oper(CurrentChar);
            }
            else if (char.IsDigit(CurrentChar)) // 数字
            {
                bool          dotFound = false;
                StringBuilder buf      = new StringBuilder();
                do
                {
                    char c = CurrentChar;
                    if (dotFound && c == '.')
                    {
                        throw new Exception("无效的数字!");
                    }
                    buf.Append(c);
                    MoveNext();
                } while (HasChar && (char.IsDigit(CurrentChar) || CurrentChar == '.'));
                MovePrev(); // 回溯一次
                token = new Number(Convert.ToDouble(buf.ToString()));
            }
            else
            {
                throw new Exception("表达式中含有无效字符:'" + CurrentChar + "'!");
            }
            MoveNext();
            return(token);
        }