如何在 C# 中初始化具有嵌套对象的对象?

How to initialize an object that has nested objects in C#?

我有一个 class,BaseRequest 有另一个 class 作为其属性之一。 class 有自己的一组属性,其中一些也是 classes,而其中一些 classes 属性是 classes。如何为 ProductOptions-GroupsToRun 和 SelectionTargets 初始化 BaseRequest?

BaseRequest.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Redundent.Models
{
    public class BaseRequest
    {
        public ProductOptions ProductOptions { get; set; }
        public string RequestingSystem { get; set; }
        public bool HasDeposit { get; set; }
        public decimal? PurchasePrice { get; set; }
        public decimal? PaymentAmount { get; set; }
    }
}

ProductOptions.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Redundent.Models
{
    public class ProductOptions
    {
        public GroupOption[] GroupsToRun { get; set; }
        public string Requestor { get; set; }
        public SelectionTargets SelectionTargets { get; set; }
        public string Partner { get; set; }

    }
}

GroupOption.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Redundent.Models
{
    public class GroupOption
    {
        public TransportationType TransportationType { get; set; }
        public RegistrationType Type { get; set; }

    }
}

TransportationType 和 RegistrationType 是枚举。 TransportationType 有汽车、飞机、船、公共汽车和 RegistrationType有Ticket, ID, Passport

SelectionTargets.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Redundent.Models
{
    public class SelectionTargets
    {
        public PricingOptionTargets PricingOptionTargets { get; set; }
        public ProductTargets ProductTargets { get; set; }
    }
}

这就是我开始的...

    var baseRequest = new BaseRequest()
            {
                
                ProductOptions = { GroupsToRun = {//not sure what to do here.  Tried TransportationType.Car but got "does not contain a definition for 'Add' and no accessible extension method 'Add'}, Requestor = "Ford", SelectionTarget = {also not sure what to do here}, Partner = 
                "Heuwett B." },

                
            };

GroupsToRun 字段是一个数组,因此必须使用数组初始化器来创建数组。查看下面的示例:

var baseRequest = new BaseRequest()
{
    ProductOptions = new ProductOptions
    {
        GroupsToRun = new[]
        {
            new GroupOption
            {
                TransportationType = new TransportationType {}
            }
        }, 
        Requestor = "Ford",
        SelectionTargets = new SelectionTargets
        {
            PricingOptionTargets = new PricingOptionTargets(),
            ProductTargets = new ProductTargets()
        }, 
        Partner = "Heuwett B."
    },
};