2011-09-20 61 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; 
} 

实际上编译到

​​

而且现在的堆栈溢出的原因是显而易见的。