您好我正在尝试创建一个类的数组并将值分配给它的字段。我的代码就像
RecordRef[] referLocation = new RecordRef[1];
referLocation[0].type = RecordType.location;
referLocation[0].internalId = "6";
但是我收到异常错误:对象引用未设置为对象的实例。代码有什么问题?
您好我正在尝试创建一个类的数组并将值分配给它的字段。我的代码就像
RecordRef[] referLocation = new RecordRef[1];
referLocation[0].type = RecordType.location;
referLocation[0].internalId = "6";
但是我收到异常错误:对象引用未设置为对象的实例。代码有什么问题?
您已经创建了对象数组RecoredRef
,但尚未在其中创建任何对象。您需要创建要使用的对象的实例:
RecordRef[] referLocation = new RecordRef[1];
// create new instance of RecordRef, which is held inside your array
referLocation[0] = new RecordRef();
referLocation[0].type = RecordType.location;
referLocation[0].internalId = "6";
您还可以使用object initializer
:
referLocation[0] = new RecordRef
{
type = RecordType.location,
internalId = "6"
};
您只初始化了数组,但 referLocation[0] 仍然为空。你想做的是:
RecordRef[] referLocation = new RecordRef[]
{
new RecordRef()
{
type = RecordType.location,
internalId = "6"
}
}
一般建议,而不是针对您的具体情况:
if(whatever == null)
语句中并进行相应处理。这是需要注意和计划的事情,因为这个错误太常见了,而且太令人沮丧,无法在以后进行故障排除。