0

您好我正在尝试创建一个类的数组并将值分配给它的字段。我的代码就像

        RecordRef[] referLocation = new RecordRef[1];
        referLocation[0].type = RecordType.location;
        referLocation[0].internalId = "6";

但是我收到异常错误:对象引用未设置为对象的实例。代码有什么问题?

4

3 回答 3

7

您已经创建了对象数组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"
};
于 2012-10-04T15:11:54.303 回答
2

您只初始化了数组,但 referLocation[0] 仍然为空。你想做的是:

RecordRef[] referLocation = new RecordRef[]
{
   new RecordRef()
   {
      type = RecordType.location,
      internalId  = "6"
   }
}
于 2012-10-04T15:13:46.303 回答
0

一般建议,而不是针对您的具体情况:

  1. 确定发生错误的行号。(Visual Studio 应该告诉你,错误消息也应该告诉你)
  2. 将潜在麻烦的代码行封装在if(whatever == null)语句中并进行相应处理。

这是需要注意和计划的事情,因为这个错误太常见了,而且太令人沮丧,无法在以后进行故障排除。

于 2012-10-04T15:12:24.893 回答