尝试将值传递到我的对象的索引中会出现错误 "System.NullReferenceException: Object reference not set to an instance of an object."

Trying to pass value into index of my Object gives an Error "System.NullReferenceException: Object reference not set to an instance of an object."

我试图在我的对象的索引中传递一个值,它给我一个错误。

System.NullReferenceException: Object reference not set to an instance of an object.

我正在使用索引创建以下对象:

RecipientInfo[] RI = new RecipientInfo[1];
RI[0].email = "email-id";
RI[0].role = RecipientRole.SIGNER;

如果你想看我的RecipientInfo方法,给你下面的方法。

public partial class RecipientInfo
{
    private string emailField;
    private System.Nullable<RecipientRole> roleField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(IsNullable = true)]
    public string email
    {
        get { return this.emailField; }
        set { this.emailField = value; }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(IsNullable = true)]
    public System.Nullable<RecipientRole> role
    {
        get { return this.roleField; }
        set { this.roleField = value; }
    }
}

为什么会出现此错误?

您的数组中没有任何内容 - 它初始化为空,其中的每个位置都是 null。您需要先创建一个 RecipientInfo,然后再对其设置属性。

最简单的更改:

RecipientInfo[] RI = new RecipientInfo[1];
RI[0] = new RecipientInfo();
RI[0].email = "email-id";
RI[0].role = RecipientRole.SIGNER;

或者,稍微好一点:

var RI = new RecipientInfo[1];

RI[0] = new RecipientInfo
{
    email = "email-id", 
    role = RecipientRole.SIGNER
};