我的课程定义如下。没有太多细节我不希望任何人能够改变这个实例化对象,或者传递给这个类构造函数的对象。
public class ItemDeliveryInfo
{
public ItemDeliveryAudit ItemDeliveryAudit
{
get
{
return this._itemDeliveryAudit;
}
}
public int ItemDeliveryAuditId
{
get
{
return this.ItemDeliveryAudit.ItemDeliveryAuditId;
}
}
public int? DeliveryDriverId
{
get
{
return this.ItemDeliveryAudit.DeliveryDriverId;
}
}
public int DeliveryId
{
get
{
return this.ItemDeliveryAudit.DeliveryId;
}
}
public int StoreId
{
get
{
return this.ItemDeliveryAudit.StoreId;
}
}
private ItemDeliveryAudit _itemDeliveryAudit;
private bool _isItemLate;
private bool _isItemOnTime;
internal ItemDeliveryInfo(ItemDeliveryAudit itemDeliveryAudit, bool itemLate, bool itemOnTime)
{
this._itemDeliveryAudit = drAssignedAudit;
this._isItemLate = itemLate;
this._isItemOnTime = itemOnTime;
}
public bool IsItemLate()
{
return this._isItemLate;
}
public bool IsItemOnTime()
{
return this._isItemOnTime;
}
}
目前构造函数用于创建单个ItemDeliveryInfo对象并成功返回我想要的对象...
ItemDeliveryInfo infoObject = new ItemDeliveryInfo(itemAudit, true, false);
但是,我无法理解如下所示的构造函数......
List<ItemDeliveryAudits> itemDeliveryAudits = // code to populate list to pass to the ctor;
List<ItemDeliveryInfo> itemDeliveryInfos = new ItemDeliveryInfo(itemDeliveryAudits, true, false);
我假设我必须创建另一个重载的构造函数来处理这个问题,但我对如何实现这一点感到茫然。任何帮助或指导将不胜感激。
答案 0 :(得分:1)
只需使用LINQ和当前的ctor:
List<ItemDeliveryInfo> itemDeliveryInfos =
itemDeliveryAudits.Select(i => new ItemDeliveryInfo(i, true, false)).ToList();
答案 1 :(得分:0)
如果您执行“new ItemDeliveryInfo”,您将始终获得“ItemDeliveryInfo”的单个实例。除了构造函数的类型之外,构造函数无法返回任何其他内容 - 它显然 可以执行类似
的操作List<ItemDeliveryInfo> itemDeliveryInfos = new ItemDeliveryInfo(itemDeliveryAudits, true, false);
您可以通过创建静态方法或工厂来完成您想要的任务,如下所示:
public static List<ItemDeliveryInfo> GetItemDeliveryInfo(List<ItemDeliveryAudits> audits) {
var list = new List<ItemDeliveryinfo>();
foreach (var deliveryAudit in audits)
{
list.Add(new ItemDeliveryInfo(deliveryAudit));
}
}
答案 2 :(得分:0)
您可以使用LINQ:
List<ItemDeliveryAudits> itemDeliveryAudits = // code to populate list to pass to the ctor;
List<ItemDeliveryInfo> itemDeliveryInfos = itemDeliveryAudits
.Select(item => new ItemDeliveryInfo(item, true, false))
.ToList();