object stack Albahari

ifo*_*ooi 0 c# object

Here is example of Albahari

public class Stack
{
int position;
object[] data = new object[10]; // Why 10 nor 1? 
public void Push (object obj) { data[position++] = obj; } //do not understood; Why there is no loop
public object Pop() { return data[--position]; } //do not understood Why there is no loop
}

Stack stack = new Stack();
stack.Push ("sausage");
string s = (string) stack.Pop(); // Downcast, so explicit cast is needed
Console.WriteLine (s); // sausage
Run Code Online (Sandbox Code Playgroud)

I rewrote code as listened here

public class Stack
{

    object[] data = new object[1];
    public void Push(object obj) { data[0] = obj; }
    public object Pop() { return data[0]; }
}

        Stack stack = new Stack();
        stack.Push("abigale ff");
        string s = (string)stack.Pop(); 
        Console.WriteLine(s); // abigale ff
Run Code Online (Sandbox Code Playgroud)

Why there is 10 in new object[10]; instead of 1 or 100 Why were used increment in data position? I do not understand how data position works.

{ data[position++] = obj; } and { return data[--position]; } How it works without loops? I try to push 2 values before pop and write it before pop but it shows me only second value

AAA*_*ddd 5

忽略这个堆栈类的所有问题,您的重构显然破坏了它。正如评论所暗示的,您缺少的关键信息实际上是++and--运算符的作用,这似乎让您相信该position字段是多余的。

++ 运算符(C# 参考)

增量运算符 (++) 将其操作数增加 1。增量运算符可以出现在其操作数之前或之后:++变量和变量++。

评论

第一种形式是前缀递增操作。运算结果是操作数递增后的

第二种形式是后缀增量运算。运算结果是操作数递增之前的

public class Stack
{
    int position;
    object[] data = new object[10]; // Why 10 nor 1? 
    public void Push (object obj) { data[position++] = obj; }
    public object Pop() { return data[--position]; }
}
Run Code Online (Sandbox Code Playgroud)

例如

当您调用时,它会按增量从数组Push中获取值datapositionposition

当您调用Pop它时,递减然后从数组中position获取值dataposition


增量页面上还有一个很好的小示例,向您展示了它是如何工作的

class MainClass
{
    static void Main()
    {
        double x;
        x = 1.5;
        Console.WriteLine(++x);
        x = 1.5;
        Console.WriteLine(x++);
        Console.WriteLine(x);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

2.5
1.5
2.5
*/
Run Code Online (Sandbox Code Playgroud)

  • @ifooi如果你再次弹出或再次推送它只会覆盖元素0 (2认同)