C#StackOverflowException

时间:2010-06-01 04:29:49

标签: c# asp.net collections stack-overflow

问题:我正在尝试更新列表。如果列表中已存在某个项目的ID,我想添加该项目的数量。如果没有,那么我想在列表中添加另一个项目。

            cart = (List<OrderItem>)Session["cart"];

            for(int counter = cart.Count-1; counter >= 0; counter--)
            {
                if (cart[counter].productId == item.productId)
                {
                    cart[counter].productQuantity += item.productQuantity;
                }
                else if (counter == 0)
                {
                    cart.Add(item);
                }
            }

cart[counter]item代表我的自定义对象的实例。目前,当我终于找到一个匹配的ID时,所有内容都显示它应该有效,但是我在自定义对象类中抛出了一个StackOverflowException。

    public int productQuantity
    {
        get
        {
            return _productQuantity;
        }
        set
        {
            productQuantity = value;
        }
    }

它被放在“套装”的开放式支架上。有人可以告诉我这到底是什么问题,因为我在过去的2个多小时里一直没有用到这一点。提前谢谢。

4 个答案:

答案 0 :(得分:8)

问题出在productQuantity的setter中

应该是:

set
    {
        _productQuantity= value;
    }

编辑(命名约定):

public class Vertex3d
{
    //fields are all declared private, which is a good practice in general 
    private int _x; 

    //The properties are declared public, but could also be private, protected, or protected internal, as desired.
    public int X
    { 
        get { return _x; } 
        set { _x = value; } 
    }
}

答案 1 :(得分:3)

productQuantity = value;替换为_productQuantity = value;(通过一遍又一遍地调用setter,你无限期地重复出现)

答案 2 :(得分:3)

为什么不直接使用它呢? public int productQuantity {get;组; }

但是这个缺陷出现在_

public int productQuantity {
    get {
        return _productQuantity;
    }
    set {
        _productQuantity = value;
    }
}

cart = (List<OrderItem>)Session["cart"];
int index = cart.Find(OrderItem => OrderItem.productId == item.productId);
if(index == -1) {
    cart.Add(item);
} else {
    cart[index].productQuantity += item.productQuantity;
}

答案 3 :(得分:2)

public int productQuantity
{
   get
   {
      return _productQuantity;
   }
   set
   {
      _productQuantity = value; //this should be an assignment to a member variable.
   }
}
相关问题