2011-09-20 65 views
0

我有一個非常簡單的C#類:asp.net C#類屬性計算器例外

namespace mybox 
{ 
    public class userAccount : IMyInterface 
    { 
     public userAccount() 
     { 
     } 
     private int _userId; 
     private string _userName; 

     public int userId 
     { 
      get { return _userId; } 
      set { userId = value; } 
     } 
     public string userName 
     { 
      get { return _userName; } 
      set { userName = value; } 
     } 

     public string list(int myUserId) 
     { 
      ... 
      myOutPut = string.Format("{0} {1} {2}", u.userId, u.userName); 
      return myOutPut.ToString(); 
     } 

    public void add() 
    { 
      pillboxDataContext db = new pillboxDataContext(); 
      userAccount newUser = new userAccount(); 
      newUser.userName = "test123"; 

      db.SubmitChanges(); 
     } 
    } 
} 

在我在Page_Load事件default.aspx.cs我試圖調用列表的方法:

protected void Page_Load(object sender, EventArgs e) 
{ 
    pillbox.userAccount myUA = new pillbox.userAccount(); 
    myUA.add(); 

// Console.WriteLine(myUA.list(1));

} 

當我調用add方法我可以看到它正試圖分配值test123的財產,但我得到以下信息:

類型「System.StackOverflowException」未處理的異常發生在App_Code.1zm0trtk.dll

任何想法我做錯了什麼?

回答

5

的問題是你定義你的屬性的方式。

您正在嘗試引用分配給設置器 中導致無限遞歸(具體而言,此行正在觸發它newUser.userName = "test123";)的值的屬性。

他們更改爲:

public int userId   
{    
    get { return _userId; }    
    set { _userId = value; }   
}   

public string userName   
{    
     get { return _userName; }    
     set { _userName = value; }   
} 
+0

好的 - 我的愚蠢的錯誤...謝謝! – webdad3

2

您需要設置專用支持字段,而不是屬性。否則,當你在整個時間內調用自己的設置時,你將進入無限遞歸。

private int _userId; 
    private string _userName; 

    public int userId 
    { 
     get { return _userId; } 
     set { _userId = value; } 
    } 
    public string userName 
    { 
     get { return _userName; } 
     set { _userName = value; } 
    } 

在你的情況,你可以只使用自動實現的屬性(我改變了外殼相匹配的指導原則):

public int UserId { get; set; } 
public string UserName { get; set; } 
+0

我的部分愚蠢的錯誤。謝謝! – webdad3

+0

它看起來像這個職位上的所有答案得到了-1的人... – driis

+0

@driis是啊我知道,仍然奇怪,當所有三個答案是正確的 –

3

這是因爲userName的自稱。你可能意味着分配領域:

此行是錯誤的:

set { userName = value; } 

你的意思是寫:

set { _userName = value; } 
+0

謝謝你......這是一個總的疏忽。 – webdad3

2

如果你重新寫你的制定者了一下,很容易看到發生了什麼。屬性上的getset實際上編譯爲方法(PropType get_PropName()void set_PropName(PropType value)),並且對該屬性的任何引用都被編譯爲調用適當的方法。所以這個代碼:

int i = myObj.MyIntProp; 
myObj.MyIntProp = 6; 

編譯成

int i = myObj.get_MyIntProp(); 
myObj.set_MyIntProp(6); 

所以你的二傳手

set 
{ 
    username = value; 
} 

實際上編譯到

​​

而且現在的堆棧溢出的原因是顯而易見的。