关于c#:对象引用未设置为具有数组的对象的实例


Object reference not set to an instance of an object w/array

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Adding C# labels to a form at Runtime

我不知道是什么导致了这个错误

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Line[] myLine = new Line[10];
int lineCount = 0;
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    if (checkBox1.CheckState == CheckState.Checked)
    {
        myLine[lineCount].setPoint(new Point(e.X, e.Y));
        ++pointCount;
        if (pointCount == 2)
        {
            pointCount = 0;
            ++lineCount;
        }
    }
}

问题在这里 P / < >

1
myLine[lineCount].setPoint(new Point(e.X, e.Y));

你需要instantiate在Line型元之前使用它。 P / < >

做: P / < >

1
2
3
4
5
6
7
8
9
10
11
if (checkBox1.CheckState == CheckState.Checked)
    {
        myLine[lineCount] = new Line(); //instantiate the array element
        myLine[lineCount].setPoint(new Point(e.X, e.Y));
        ++pointCount;
        if (pointCount == 2)
        {
            pointCount = 0;
            ++lineCount;
        }
}

看来,线的类,(参考型)如果你创建一个阵列的参考类型的所有元素的阵列中,然后把"value of null违约,你可以打电话到审法在null对象。 P / < >

例如,从msdn单一dimension arrays P / < >

1
SomeType[] array4 = new SomeType[10];

The result of this statement depends on whether SomeType is a value
type or a reference type. If it is a value type, the statement results
in creating an array of 10 instances of the type SomeType. If SomeType
is a reference type, the statement creates an array of 10 elements,
each of which is initialized to a null reference.