我有三个系列:
private ICollection<FPTAssetClassAsset> wrassets;
private ICollection<FPTFundAsset> wrfunds;
private ICollection<FPTManagedStrategyAsset> wrstrats;
Run Code Online (Sandbox Code Playgroud)
如果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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您Array.Empty<T>只是在寻找不会在阅读时崩溃的东西,那么您可以使用它,直到您可以抽出时间用您认真使用的东西替换它:
private ICollection<FPTAssetClassAsset> wrassets = Array.Empty<FPTAssetClassAsset>();
private ICollection<FPTFundAsset> wrfunds = Array.Empty<FPTFundAsset>();
private ICollection<FPTManagedStrategyAsset> wrstrats = Array.Empty<FPTManagedStrategyAsset>();
Run Code Online (Sandbox Code Playgroud)
好吧,您始终可以null在添加前进行检查。或者,您可以将其变成属性:
private ICollection<FPTAssetClassAsset> wrassets
{
get { return _wrassets == null ? new List<FPTAssetClassAsset>() : _wrassets; }
}
private ICollection<FPTAssetClassAsset> _wrassets;
Run Code Online (Sandbox Code Playgroud)
在foreach循环之前初始化您的集合,这样它们将始终具有一个值:
private ICollection<FPTAssetClassAsset> wrassets = new Collection<FPTAssetClassAsset>();
private ICollection<FPTFundAsset> wrfunds = new Collection<FPTFundAsset>();
private ICollection<FPTManagedStrategyAsset> wrstrats = new Collection<FPTManagedStrategyAsset>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16495 次 |
| 最近记录: |