将值读入List对象-未将对象引用设置为对象的实例

问题描述:

尝试将值加载到List对象中时,出现对象引用未设置为对象实例"错误.

Trying to load values into a List object, I get the "Object reference not set to an instance of an object" error.

(为简化起见,已编辑问题)

(edited question to simplify it)

MyVec.h列表(仅基本):

MyVec.h listing (essentials only):

ref class MyVec
{
public:
    List<double>^ MyVector;

MyVec(void);
};

MyVec.cpp列表(仅必需):

MyVec.cpp listing (essentials only):

#include "MyVec.h"

MyVec::MyVec(void)
{
}

Form.h列表(仅必需):

Form.h listing (essentials only):

MyVec^ TestVec = gcnew MyVec();
double MyDouble = 1.002;
TestVec->MyVector->Add(MyDouble);
textBox1->Text = TestVec->MyVector[0].ToString() + "\r\n";

在尝试将MyDouble分配给TestVec时出现错误:TestVec-> MyVector-> Add(MyDouble)

I get the error where I try to assign MyDouble to TestVec: TestVec->MyVector->Add(MyDouble)

在汽车"窗口中(除其他外)显示TestVec-> MyVector未定义值

In the Autos window it says (amongst other things) TestVec->MyVector undefined value

怎么了?

此更改应该可以解决问题:

This change should solve the problem:

MyVec::MyVec(void)
{
    MyVector = gcnew List<double>();
}

类成员MyVector是initilly空引用.使用之前,您需要对其进行初始化,并且MyVec构造函数是执行此操作的适当位置.

Class member MyVector is initailly null reference. You need to initialize it before using, and MyVec constructor is appropriate place to do it.