对象堆Albahari

时间:2018-04-13 04:41:22

标签: c# object

这是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

我重写了这里听到的代码

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

为什么new object[10];中有10个而不是1个或100个 为什么在数据位置使用增量?我不明白数据位置是如何工作的。

{ data[position++] = obj; }{ return data[--position]; }如何在没有循环的情况下工作? 我尝试在pop之前推送2个值并在pop之前写入它,但它只显示第二个值

1 个答案:

答案 0 :(得分:4)

忽略这个堆栈类的所有问题,你的重构显然打破了它。正如评论所提到的,您缺少的关键信息实际上是++--运算符所做的事情,这似乎让您相信position字段是多余的。

++ Operator (C# Reference)

  

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

     

<强>说明

     

第一种形式是前缀增量操作。 结果   操作是操作数增加后的值

     

第二种形式是后缀增量操作。 结果   operation 是操作数的值   在它增加之前

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]; }
}

例如

当您致电Push时,它会从data的{​​{1}}数组中获取值,然后递增position

当您致电position时,它会递减Pop,然后从position

获取data数组中的值

增量页面上还有一个很好的小例子,它会告诉你它是如何工作的

position

<强>输出

class MainClass
{
    static void Main()
    {
        double x;
        x = 1.5;
        Console.WriteLine(++x);
        x = 1.5;
        Console.WriteLine(x++);
        Console.WriteLine(x);
    }
}