c# - 在构造函数中访问数组

标签 c# arrays constructor stack tdd

这是做作业的。

我已经用谷歌搜索了这个并在stackoverflow中搜索,但我似乎找不到答案。也许我的术语不正确。

我正在为一个类学习 TDD,而我的 C# 技能生疏且有限。

我正在尝试编写一个堆栈类。当我尝试在构造函数中启动一个数组时,这些方法无法访问它。

我敢肯定,我缺少一些简单的东西。
这是我到目前为止尝试过的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tdd_programmingTest
{
    class Stack
    {
        int index = 0;

        public Stack()
        {
            int[] items;
        }

        public void Push(int p)
        {
            items[index] = p;
            index++;
        }

        public int Pop()
        {
            index--;
            return items[index];
        }

        internal int IndexState()
        {
            return index;
        }
    }
}

我不是在找人为我编写代码,只是为我指明正确的方向。谢谢你。

最佳答案

你这里有一个local variable :

    public Stack()
    {
        int[] items;
    }

它仅在 Stack() 内部退出构造函数,并且仅在其执行的生命周期内。

您需要申报items作为 field (成员变量):
class Stack
{
    private int index = 0;
    private int[] items;       // <-- move it here, and mark it private

    public Stack()
    {

    }
    // ...
}

但是你有更大的问题。这只是对您尚未创建的数组的引用。

因此,您需要实例化一个数组:
int[] items = new int[SIZE];

...但是您将使用什么尺寸?一旦你创建了数组,它就不能增长。一旦空间不足,您将不得不分配一个更大的数组并复制它。这个自动自扩是多少ADT的幕后工作。

说到空间不足,你最好注意数组在Push()中的边界。和 Pop() !

编辑:所以你需要指定一个大小。只需在构造函数中添加一个参数。
class Stack
{
    private int index = 0;
    private int[] items;

    public Stack(int initialSize)
    {
        items = new int[initialSize];
    }

    public Stack() : Stack(100)
    {
    }
}

关于c# - 在构造函数中访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21472103/

相关文章:

c# - 子 XElement 的索引

c# - 为什么 '+' + 短转换为 44

ios - Swift 中的数组不计算对象

c# - 如何分解 450 行代码的 View 模型

c# - 具有 ExpectedException 的 XUnit 和 MSTest 返回不同的结果

javascript - SumoSelect 没有选择数组中的所有值

javascript - Mongoose 查找并创建多维数组

c++ - 来自字符串的构造函数 VS 来自字符串的词法转换?

javascript - 绑定(bind)要在 Function 构造函数内使用的函数

c++ - "Ambiguous resolution"选择性构造函数继承错误