[英]get set property always returns null
我声明一个属性-当我在开发环境中工作时,当我访问登台环境时它可以正常工作,但始终返回null。 为什么会这样呢? 两种环境中的代码都不会改变。 这是代码。
private ProductCollection _productCollection;
public ProductCollection ProdCollection
{
get
{
_productCollection = MWProductReviewHelper.GetDistinctProductFromTill(StoreId, TDPId, ReceiptId);
if (_productCollection.Count > 0)
return _productCollection;
else
return null;
}
}
private ProductCollection _guaranteedProductCollection = new ProductCollection();
public ProductCollection GuaranteedProductCollections
{
get
{
if (_guaranteedProductCollection.Count > 0)
{
return _guaranteedProductCollection;
}
else
{
return _guaranteedProductCollection = MWProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection); // the problem appears to be here...
}
}
}
我访问就是这样。
if (GuaranteedProductCollections.Count > 0)
{
ProductCollection _prodCollection = GuaranteedProductCollections; // return null
}
它内部始终只有一个产品-当我在断点处看到该产品。
您是否尝试过将这行设置为两行? 看起来它可能在设置完成之前就返回了。
public ProductCollection GuaranteedProductCollections
{
get
{
if (_guaranteedProductCollection.Count > 0)
{
return _guaranteedProductCollection;
}
else
{
_guaranteedProductCollection = MWProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection); // the problem appears to be here...
return _guaranteedProductCollection;
}
}
}
如果您的GuaranteedProductCollections
属性返回null,则可能是因为:
MWProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection)
返回null。 _guaranteedProductCollection
设置为null(这不太可能,因为_guaranteedProductCollection
在测试其计数时不为null,因为这会引发异常) 顺便说一句,通常在以这种方式初始化集合时,最好使用null
表示未初始化的集合,以允许初始化集合但为空的情况。 我会像这样实现您的财产:
public ProductCollection GuaranteedProductCollections
{
get
{
if (_guaranteedProductCollection == null)
{
_guaranteedProductCollection = WProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection);
}
return _guaranteedProductCollection;
}
}
可以使用null-coalescing(??)运算符将其简化为1行
public ProductCollection GuaranteedProductCollections
{
get
{
return _guaranteedProductCollection
?? _guaranteedProductCollection = WProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.