将List <t>分配给属性C#时出错System.NullReferenceException

时间:2017-04-05 20:49:11

标签: c# list nullreferenceexception

这不是我不知道什么是NullRefrenceException。有一些不确定的情况我得到了错误。

我试图将值分配给某些类的属性。

这是我的课程。

// These classes are in EmailProcess namspace
public class ActionedEmailReport
{
    public Message Message { get; set; }
    public string SaveToSentItems { get; set; }
}

public class ToRecipient
{
    public EmailObject.EmailAddress EmailAddress { get; set; }
}

public class Message
{
    public string Subject { get; set; }
    public Body Body { get; set; }
    public List<ToRecipient> ToRecipients { get; set; }
}

public class Body
{
    public string ContentType { get; set; }
    public string Content { get; set; }
}

// Below class in EmailObject namespace.
namespace EmailObject
{
   public class EmailAddress
   {
      public string Address { get; set; }
   }
}

这是我的代码,用于为类的属性赋值。

public void EmailProcessing(string recepeint)
{
   ActionedEmailReport actionedReport = new ActionedEmailReport();
   List<ToRecipient>toRecipient = new List<ToRecipient>();
   EmailObject.EmailAddress emailAddress= new EmailObject.EmailAddress();
   emailAddress.Address = recepeint;
   toRecipient.Add(new ToRecipient()
{
   EmailAddress=emailAddress
});

   // I'm getting error on the below line.    
   actionedReport.Message.ToRecipients = toRecipient;
   actionedReport.Message.Body.Content = "Hello";
   actionedReport.Message.Body.ContentType = "Text";
   actionedReport.SaveToSentItems = "True";
   actionedReport.Message.Subject = "Demo Email"
}

actionedReport.Message.ToRecipients = toRec;行上我收到错误

  

System.NullReferenceException:未将对象引用设置为对象的实例。

我已正确检查输入并确定我为toRecipient分配了一些值,然后我收到此错误的原因。这让我发疯了。

1 个答案:

答案 0 :(得分:1)

Message中的ActionedEmailReport属性未被实例化。您需要在ActionedEmailReportMessage属性中添加构造函数。 您可能也需要对Body类中的Message属性执行相同的操作。