如何避免在C#Console Project中未将对象引用设置为对象的实例

use*_*482 0 c#

嗨,我正在尝试创建一个类的数组,并为其字段分配值.我的代码就像

        RecordRef[] referLocation = new RecordRef[1];
        referLocation[0].type = RecordType.location;
        referLocation[0].internalId = "6";
Run Code Online (Sandbox Code Playgroud)

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

Zbi*_*iew 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";
Run Code Online (Sandbox Code Playgroud)

您也可以使用object initializer:

referLocation[0] = new RecordRef
{ 
    type = RecordType.location,
    internalId = "6"
};
Run Code Online (Sandbox Code Playgroud)