我有三个系列:
private ICollection<FPTAssetClassAsset> wrassets;
private ICollection<FPTFundAsset> wrfunds;
private ICollection<FPTManagedStrategyAsset> wrstrats;
如果foreach循环返回0个对象,则集合不会被设置,因此为null。 当我将这个icollection(Union)添加到另一个icollection时,它失败了:“Value不能为null”因为icollection为null,而不是Empty。如何将此集合设置为空?
循环:
public void GetWrapperAssets(FPT fpt)
{
foreach (var w in fpt.CouttsPositionSection.Wrappers
.Union(fpt.StandAloneSection.Wrappers)
.Union(fpt.BespokePropositionSection.Wrappers)
.Union(fpt.NonCouttsPositionSection.Wrappers)
)
{
foreach (var a in w.UnderlyingAssets.OfType<FPTManagedStrategyAsset>())
{
wrstrats.Add(a);
}
foreach (var a in w.UnderlyingAssets.OfType<FPTAssetClassAsset>())
{
wrassets.Add(a);
}
foreach (var a in w.UnderlyingAssets.OfType<FPTFundAsset>())
{
wrfunds.Add(a);
}
}
}
答案 0 :(得分:4)
嗯,您可以在添加之前始终检查null
。或者你可以把它变成一个属性:
private ICollection<FPTAssetClassAsset> wrassets
{
get { return _wrassets == null ? new List<FPTAssetClassAsset>() : _wrassets; }
}
private ICollection<FPTAssetClassAsset> _wrassets;
答案 1 :(得分:4)
在foreach循环之前初始化你的集合,这样它们总是有一个值:
private ICollection<FPTAssetClassAsset> wrassets = new Collection<FPTAssetClassAsset>();
private ICollection<FPTFundAsset> wrfunds = new Collection<FPTFundAsset>();
private ICollection<FPTManagedStrategyAsset> wrstrats = new Collection<FPTManagedStrategyAsset>();