C#StackOverflowException

KSw*_*t87 1 c# asp.net stack-overflow collections

问题:我正在尝试更新列表.如果列表中已存在某个项目的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);
                }
            }
Run Code Online (Sandbox Code Playgroud)

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

    public int productQuantity
    {
        get
        {
            return _productQuantity;
        }
        set
        {
            productQuantity = value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Voo*_*ild 8

问题出在productQuantity的setter中

它应该是:

set
    {
        _productQuantity= value;
    }
Run Code Online (Sandbox Code Playgroud)

编辑(命名约定):

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; } 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果可以的话,+1 1000次; 像这样的微妙错误是配对编程的一个原因(或者至少让新鲜的眼睛盯着你的代码). (2认同)