处理堆栈和接口的问题

Problems with handling a Stack along with a Interface

所以我的 Console Application 有问题。我正在尝试使用某些方法在我的 class 中实现一个接口。但我真的无法掌握它。

我遇到的问题是什么也没有发生。当我启动应用程序时,控制台弹出并运行代码并等待 Console.Read() 发生。

希望您能理解,代码比较简单。我会 post Interface, Class and program code.

接口代码:

public interface IStackInterface
{
    char peek();
    char pop();
    void push(char nytt);
    bool isEmpty();
}

Class代码:

public class StackClass : IStackInterface
{
    Stack<char> stacken = new Stack<char>();

    public StackClass()
    {

    }
    public bool isEmpty()
    {
        if (stacken.Count == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public char peek()
    {
        return stacken.Peek();
    }

    public char pop()
    {
        return stacken.Pop();

    }

    public void push(char nytt)
    {
        stacken.Push(nytt);
    }
}

程序代码:

static void Main(string[] args)
        {
                StackClass stacken = new StackClass();

                try
                {
                    stacken.push('t'); stacken.push('s');
                    stacken.push('ä'); stacken.push('b');
                    stacken.push(' ');
                    stacken.push('r'); stacken.push('ä');
                    stacken.push(' '); stacken.push('m');
                    stacken.push('o'); stacken.push('g');
                    stacken.push('a'); stacken.push('L');
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);
                }

                while (!stacken.isEmpty())
                {
                    Console.WriteLine(stacken.pop());
                }
                Console.Read();
        }

此致。

您的代码没有按照您的预期运行,纯粹是因为您对 isEmpty 的实现方式不对。当计数为零时,它应该 return true

您的代码中存在逻辑错误...isEmpty returns 与您想要的相反。另外,你可以这样优化它:

public bool isEmpty()
{
    return (stacken.Count == 0);
}

甚至:

public bool isEmpty()
{
    return stacken == null ? true : (stacken.Count == 0);
}