无法创建随机值

Having trouble creating random values

所以我创建了包含 int 和 double 的 Pairs class,我想用我的 array class 通过创建随机值,但我在第 19 行得到 System.NullReferenceException 我的数组 class.

这是我的一对 class

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 和摘要 class

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

此外,使用这个摘要是否值得 class 我从我大学的参考资料中使用了这个 假如。我必须创建一个快速排序算法,对数组和链表中的对进行排序并对其进行分析。

data = new Pair[n];

这将创建一个新数组 空引用

循环应该是

    for (int i = 0; i < n; i++)
    {
        data[i] = new Pair(rand.Next(), rand.NextDouble())
    }

当我们查看您的代码时:您在这里做了一个很好的尝试来制作不可变对,但它可能会更好。你想要的是:

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

    public int Integer { get; private set; }
    public double Double { get; private set; }
}

更短、更安全、更清晰。

您的代码存在的问题是您只初始化了 MyDataArray 中的数据数组。创建实例数组时,它只初始化数组的引用,而不是数组中的实际实例。这些引用都指向 null。因此,当您尝试在数据数组中设置第 i 个 Pair 实例的整数成员时:

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

您实际上是在尝试设置 null 的整数成员,该成员不存在。

...
null.integer = rand.Next();
...

要解决此问题,只需为循环中的每个数据索引创建一个新的 Pair 实例。

...
for (int i = 0; i < n; i++)
{
    data[i] = new Pair();
    data[i].integer = rand.Next();
    data[i].doubl = rand.NextDouble();

}
...

更好的是,您可以使用您创建的构造函数,它需要参数来设置整数并在构造时加倍以简化循环中的代码。

...
for (int i = 0; i < n; i++)
{
    data[i] = new Pair(rand.Next(), rand.NextDouble());
}
...