2010-06-01 29 views
1

問題:我正在嘗試更新列表。如果某個項目的ID已經存在於列表中,我想添加到該項目的數量。如果沒有,那麼我想添加另一個項目到列表中。C#StackOverflowException

  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; 
     } 
    } 

它被扔到「set」的開括號處。請問有人能告訴我什麼是錯誤的,因爲我在過去的兩個半小時內一直沒有結果。先謝謝你。

+1

在一個側面說明,詞典或HashSet的可能更好地爲你;在這種情況下不需要收集遍歷。 – 2010-06-01 04:35:47

+0

是否有返回_productQuantity並設置productQuantity的原因?我通常使用相同的支持成員。 – 2010-06-01 04:38:11

+0

@Rob:我認爲這是一個命名約定/數據隱藏的事情。我不記得我第一次看到它的時間/地點,但我一直在編寫我的學校項目,直到現在我從未遇到過問題。我來自Java背景,所以C#中的set/get屬性 - 在Java中我實際上必須爲該功能編寫getter和setter方法。我想我可能剛剛在某處看到了一些代碼片段,並且在我的腦海中混雜了一些東西。 – KSwift87 2010-06-01 05:07:21

回答

8

問題是在你的產品數量

制定者應改爲:

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; } 
    } 
} 
+0

在旁註:我沒有在你的代碼中找到其他的錯誤,只是這個特定的代碼。如果可以的話, – VoodooChild 2010-06-01 04:37:05

+2

+1 1,000次;像這樣的微妙的錯誤是配對編程的原因(或者至少有新鮮的眼睛盯着你的代碼)。 – 2010-06-01 04:39:28

+0

親愛的上帝,你好。我也沒有期望得到如此快速的迴應。謝謝謝謝!我不記得我在哪裏學習編碼屬性,但由於某些原因,我從未將變量命名爲與我在獲取中所做的相同。我認爲這是一個命名約定以及數據隱藏的事情......所以另一個問題是:什麼是適當的命名約定的屬性? – KSwift87 2010-06-01 04:56:49

3

更換productQuantity = value;_productQuantity = value;(你經常無限地通過一次又一次地調用setter)

+0

謝謝你的迴應,但VooDoo的孩子是第一個。我仍然給你一個+1。 :-) – KSwift87 2010-06-01 05:07:56

2
public int productQuantity 
{ 
    get 
    { 
     return _productQuantity; 
    } 
    set 
    { 
     _productQuantity = value; //this should be an assignment to a member variable. 
    } 
} 
+0

謝謝你的迴應,但VooDoo的孩子是第一個。我仍然給你一個+1。 :-) – KSwift87 2010-06-01 04:58:01

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; 
} 
+0

謝謝你的迴應,但VooDoo的孩子是第一個。我仍然給你一個+1。 :-)至於你的建議......我從來沒有正式教過Lambda表達式,雖然我從未真正理解它們的用途/操作方式,但我已經看到了它們。 – KSwift87 2010-06-01 05:01:21

+0

你絕對應該閱讀關於他們的教程。他們很容易遵循(無論如何是基本的),非常方便 – VoodooChild 2010-06-01 05:41:26

相關問題