如何初始化在C#中有嵌套对象的对象?
我有一个类BaseRequest,它有另一个类作为其属性之一。该类有自己的属性集,其中一些属性也是类,而这些类中的一些属性是类。如何初始化ProductOptions GroupsToRun和SelectionTargets的BaseRequest BaseRequest.cs如何初始化在C#中有嵌套对象的对象?,c#,class,object,inner-classes,C#,Class,Object,Inner Classes,我有一个类BaseRequest,它有另一个类作为其属性之一。该类有自己的属性集,其中一些属性也是类,而这些类中的一些属性是类。如何初始化ProductOptions GroupsToRun和SelectionTargets的BaseRequest BaseRequest.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Re
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是枚举。运输类型有汽车、飞机、轮船、公共汽车和火车
注册类型包括机票、身份证、护照
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=新的ProductOptions
{
GroupsToRun=new[]
{
新组选项
{
TransportationType=新的TransportationType{}
}
},
请求者=“福特”,
SelectionTargets=新的SelectionTargets
{
PricingOptionTargets=新PricingOptionTargets(),
ProductTargets=新的ProductTargets()
},
Partner=“Heuwett B.”
},
};
GroupsToRun字段是一个数组,因此必须使用数组初始化器来创建数组。检查以下示例:
var baseRequest=new baseRequest()
{
ProductOptions=新的ProductOptions
{
GroupsToRun=new[]
{
新组选项
{
TransportationType=新的TransportationType{}
}
},
请求者=“福特”,
SelectionTargets=新的SelectionTargets
{
PricingOptionTargets=新PricingOptionTargets(),
ProductTargets=新的ProductTargets()
},
Partner=“Heuwett B.”
},
};