示例#1
0
        public static CalcItem Parse(string s)
        {
            var item = new CalcItem();

            if (double.TryParse(s, out item.value))
            {
                item.op = Operator.Push;
            }
            else
            {
                if (s.Length > 1)
                {
                    throw new ArgumentException("If not a number, string must be a single character");
                }

                item.op = s switch
                {
                    "+" => Operator.Add,
                    "-" => Operator.Subtract,
                    "*" => Operator.Multiply,
                    "/" => Operator.Divide,
                    _ => throw new ArgumentException("Unrecognized operator")
                };
            }

            return(item);
        }
示例#2
0
        public void PerformSingle(CalcItem item)
        {
            if (item.op == Operator.Push)
            {
                _stack.Push(item);
            }
            else
            {
                if (_stack.Count < 2)
                {
                    throw new Exception("Not enough values to operate on");
                }

                var val2 = _stack.Pop().value;
                var val1 = _stack.Pop().value;
                PerformSingle(CalcItem.Value(item.op switch
                {
                    Operator.Add => val1 + val2,
                    Operator.Subtract => val1 - val2,
                    Operator.Multiply => val1 * val2,
                    Operator.Divide => val1 / val2
                }));