创建随机值时遇到麻烦

问题描述 投票:0回答:2

所以我创建了包含int和double的Pairs类,我想用我的数组创建它们的数组通过创建随机值来创建数组类,但是我在第19行的System.NullReferenceException我的数组类。

这是我的双人班

class Pair
{

    public int integer = 0;
    public double doubl = 0.0;

    public Pair(int integer, double doubl)
    {
        this.integer = integer;
        this.doubl = doubl;
    }

    public Pair()
    {

    }
    public int Integer() { return integer; }
    public double Doubl() { return doubl; }
}

这是我的数组类和抽象类

class MyDataArray : DataArray
{

    Pair[] data;
    int operations = 0;

    public MyDataArray(int n, int seed)
    {
        data = new Pair[n];
        Random rand = new Random(seed);
        for (int i = 0; i < n; i++)
        {
            data[i].integer = rand.Next(); //I get error here
            data[i].doubl = rand.NextDouble();

        }

    }

    public int integer(int index)
    {
        return data[index].integer;

    }

    public double doubl(int index)
    {
        return data[index].doubl;
    }
}

abstract class DataArray
{

    public int operations { get; set; }
    public abstract void Swap(int i, int j);
    public abstract void Swap2(int i, int high);
}

同样,使用这个抽象类也值得吗?提供。我必须创建一个快速排序算法,以对数组和链接列表中的对进行排序并对其进行分析。

c# class quicksort
2个回答
0
投票
代码的问题在于,您仅在MyDataArray中初始化数据数组。创建实例数组时,它仅初始化该数组的引用,而不初始化数组中的实际实例。这些引用均指向null。因此,当您尝试在数据数组中设置第i个Pair实例的整数成员时:

... data[i].integer = rand.Next(); ...


2
投票
data = new Pair[n];
© www.soinside.com 2019 - 2024. All rights reserved.