如何避免对象引用未设置为C#Console项目中对象的实例

如何避免对象引用未设置为C#Console项目中对象的实例,c#,C#,嗨,我正在尝试创建一个类的数组,并给它的字段赋值。我的代码是 RecordRef[] referLocation = new RecordRef[1]; referLocation[0].type = RecordType.location; referLocation[0].internalId = "6"; 但我得到了异常错误:对象引用未设置为对象的实例。 代码中有什么错误?您已经创建了RecoredRef对象的数组,但没有在其中创建任何对象

嗨,我正在尝试创建一个类的数组,并给它的字段赋值。我的代码是

        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";
您也可以使用:


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

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

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

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

    RecordRef[] referLocation = new RecordRef[]
    {
       new RecordRef()
       {
          type = RecordType.location,
          internalId  = "6"
       }
    }
    

    显然,@des正确地指出了它的具体位置。我只是把它作为一种通用模式扔出去,因为user1683482一开始并没有检查空引用。良好的实践和所有。有时您确实希望在项目为空时不运行代码,但并不总是这样。有时候这只是你逻辑上的一个缺陷,就像这里的情况一样。有时项目的创建会被跳过、中断等(这里就是这种情况)。有时变量一开始就不应该为null。事实上,如果我在数组的维数之前就知道,出于同样的原因,我更喜欢使用集合和对象初始值设定项。这只是一种避免空引用异常的方法。
    RecordRef[] referLocation = new RecordRef[]
    {
       new RecordRef()
       {
          type = RecordType.location,
          internalId  = "6"
       }
    }