C#嵌套属性

时间:2019-03-14 19:23:07

标签: c# class

我有一个像这样的模型,其中包括OwnerProductRegistration和AttachmentList。

public class OwnerProductRegistration
{
    public string CustomerFirstName { get; set; }
    public string CustomerPhoneMobile { get; set; }
    public List<AttachmentList> AttachmentLists { get; set; }
}

public class AttachmentList
{
    public string FileName { get; set; }
    public string Description { get; set; }
}

OwnerProductRegistration model = new OwnerProductRegistration();
AttachmentList attachmentList = new AttachmentList();

model.CustomerFirstName = "Test";
model.CustomerPhoneMobile = "1234567890";

attachmentList.FileName = "FileNameTest";
attachmentList.Description = "foo";

我想发送包含AttachmentList数据的整个“ OwnerProductRegistration”模型。当我检查模型的值内容时,它将AttachmentList显示为null。如何在模型中包含AttachmentList数据?

3 个答案:

答案 0 :(得分:3)

您必须首先实例化模型属性上的列表,然后向其中添加附件列表。您可以像这样完成两者:

model.CustomerFirstName = "Test";
model.CustomerPhoneMobile = "1234567890";

attachmentList.FileName = "FileNameTest";
attachmentList.Description = "foo";

model.AttachmentLists = new List<AttachmentList> { attachmentList };

如果您不想使用集合初始化程序,则可以按如下所示拆分操作:

model.AttachmentLists = new List<AttachmentList>();
model.AttachmentLists.Add(attachmentList);

答案 1 :(得分:2)

您没有在任何地方设置AttachmentLists属性。尝试一下,它与您的相似,但是属性设置在最后一行。

public class OwnerProductRegistration
{
  public string CustomerFirstName { get; set; }
  public string CustomerPhoneMobile { get; set; }
  public List<AttachmentList> AttachmentLists { get; set; }
}

public class AttachmentList
{
  public string FileName { get; set; }
  public string Description { get; set; }
}

OwnerProductRegistration model = new OwnerProductRegistration();
AttachmentList attachmentList = new AttachmentList();

model.CustomerFirstName = "Test";
model.CustomerPhoneMobile = "1234567890";

attachmentList.FileName = "FileNameTest";
attachmentList.Description = "foo";

model.AttachmentLists = new List<AttachmentList> { attachmentList };

答案 2 :(得分:0)

您还可以使用C#3中提供的 Object Initializer Collection initializer 语法,如下所示

OwnerProductRegistration model = new OwnerProductRegistration
{
  CustomerFirstName = "Test",
  CustomerPhoneMobile = "1234567890",
  AttachmentLists = new List<AttachmentList>
  {
    new AttachmentList
    {
      FileName = "FileNameTest",
      Description = "foo",
    }
  }
}