从构造函数访问更新的数组

时间:2015-12-04 09:45:50

标签: c# arrays custom-lists

我有一个参数化构造函数和一个默认构造函数。它们都创建了一个x长度的新对象数组,但是,当我尝试在Add方法中访问数组时,它返回值" null"。我无法在字段中初始化数组,因为我不知道用户希望它的大小,但我不知道如何访问“更新的”数据。数组稍后在代码中。我在代码行上得到一个NullReferenceException():if(count> data.Length)因为数据的值为null。

class CustomList
{
    private int count;
    private String[] data;

    public int Count
    {
        get { return count; }
    }
    public CustomList(int arrayNum)
    {
        String[] data = new String[arrayNum];
    }
    public CustomList(): this(4)
    {
    }

    public void Add (String item)
    {
        if (count > data.Length)
        {
            String[] temp = new String[count * 2];
            for (int i = 0; i < data.Length; i++)
            {
                temp[i] = data[i];
            }
            data = temp;
        }
        data[count] = item;
        count++;
    }

2 个答案:

答案 0 :(得分:4)

改变这个:

public CustomList(int arrayNum)
{
    String[] data = new String[arrayNum];
}

对此:

public CustomList(int arrayNum)
{
    data = new String[arrayNum];
}

您在构造函数中意外创建了一个局部变量,而不是您想要分配的字段。

答案 1 :(得分:2)

更改您的代码。

构造函数中的数据对象是局部变量。 而且您没有初始化实例数据对象。

class CustomList
{
private int count;
private String[] data;

public int Count
{
    get { return count; }
}
public CustomList(int arrayNum)
{
     data = new String[arrayNum];
}
public CustomList(): this(4)
{
}

public void Add (String item)
{
    if (count > data.Length)
    {
        String[] temp = new String[count * 2];
        for (int i = 0; i < data.Length; i++)
        {
            temp[i] = data[i];
        }
        data = temp;
    }
    data[count] = item;
    count++;
}