C#Array - 未将对象引用设置为对象的实例。 [英] C# Array - Object reference not set to an instance of an object.

查看:87
本文介绍了C#Array - 未将对象引用设置为对象的实例。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试创建随机点的快速尝试会继续返回

,并显示错误消息:对象引用未设置为对象的实例。。



以下是代码:



So, a quick attempt of me trying to create random points it continuesly returns
with an error saying: "Object reference not set to an instance of an object.".

Here is the code:

public void GeneratePoints(int Width, int MaximumGain, int Frequency)
{
    /* Create a random. */
    Random rd = new Random();

    /* Initialize the Points array. */
    double[] ReturnPoints = new double[Width];

    /* Set a starting point. */
    ReturnPoints[Width / 2] = rd.Next(0, MaximumGain);

    /* Generate random points after the middle.*/
    for (int i = Width / 2 + 1; i < Width; i++)
    {
        // -- Strangly, this is the error.
        ReturnPoints[i] = rd.Next(0, (int)Points[i - 1]);
    }

    /* Generate random points before the middle.*/
    for (int i = Width / 2 - 1; i > 0; i--)
    {
        ReturnPoints[i] = rd.Next(0, (int)Points[i + 1]);
    }

    /* Set the points. */
    Points = ReturnPoints;
}

推荐答案

这意味着您正在尝试访问数组元素,但数组不包含数组的这个元素已经声明但从未初始化。



查看我过去的答案: vb.net中的NullReferenceException [ ^ ]
This means that you are trying to access to array element, but array does not contain this element of array has been declared but never initialized.

See my past answer: NullReferenceException in vb.net[^]


目前尚不清楚您要实现的目标,但如果您在某处初始化Points,则不应出现对象引用错误。



It''s not clear what you are trying to achieve but if you initialize Points also somewhere then the object reference error should not come.

/* Initialize the Points array. */
double[] ReturnPoints = new double[Width];
// Add this line of code.
int[] Points = new int[Width];





否则你必须在任何地方使用ReturnPoints积分





Or else you have to use ReturnPoints itself where ever you are using Points

/* Generate random points after the middle.*/
for (int i = Width / 2 + 1; i < Width; i++)
{
    // -- Strangly, this is the error.
    //ReturnPoints[i] = rd.Next(0, (int)Points[i - 1]);
    ReturnPoints[i] = rd.Next(0, (int)ReturnPoints[i - 1]);
}

/* Generate random points before the middle.*/
for (int i = Width / 2 - 1; i > 0; i--)
{
    //ReturnPoints[i] = rd.Next(0, (int)Points[i + 1]);
    ReturnPoints[i] = rd.Next(0, (int)ReturnPoints[i + 1]);
}


这篇关于C#Array - 未将对象引用设置为对象的实例。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆