get set属性始终返回null

时间:2012-08-16 09:15:30

标签: c# asp.net

我正在声明一个属性 - 当我在我的开发环境中工作时它工作正常但是当我访问临时环境时,它总是返回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
}

它里面总有一个产品 - 当我放入一个断点时,我可以看到它。

2 个答案:

答案 0 :(得分:2)

你试过在两条线上碰撞那套吗?看起来它可能在集合完成之前返回。

public ProductCollection GuaranteedProductCollections
      {
        get
          {
            if (_guaranteedProductCollection.Count > 0)
              {
                 return _guaranteedProductCollection;
              }
            else
              {
                _guaranteedProductCollection = MWProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection);  // the problem appears to be here... 
                return _guaranteedProductCollection;
              }
           }
      }

答案 1 :(得分:1)

如果您的GuaranteedProductCollections属性返回null,则它必须是因为:

  • MWProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection)返回null。
  • 其他一些事情是将_guaranteedProductCollection设置为null(这不太可能,因为_guaranteedProductCollection在测试其计数时不为空,因为这会引发异常)

顺便说一句,通常在以这种方式初始化集合时,最好使用null来表示未初始化的集合,以允许初始化集合的情况,但是为空。我会像这样实现你的财产:

public ProductCollection GuaranteedProductCollections
{
    get
    {
        if (_guaranteedProductCollection == null)
        {
            _guaranteedProductCollection = WProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection);
        }
        return _guaranteedProductCollection;
    }
}

这可以简化为null-coalescing (??) operator

的1行
public ProductCollection GuaranteedProductCollections
{
    get
    {
        return _guaranteedProductCollection
            ?? _guaranteedProductCollection = WProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection);
    }
}
相关问题