Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
asp.net c#类属性堆栈溢出异常_C#_Asp.net - Fatal编程技术网

asp.net c#类属性堆栈溢出异常

asp.net c#类属性堆栈溢出异常,c#,asp.net,C#,Asp.net,我有一个非常简单的C#类: 在页面加载事件的my default.aspx.cs中,我试图调用list方法: protected void Page_Load(object sender, EventArgs e) { pillbox.userAccount myUA = new pillbox.userAccount(); myUA.add(); //Console.WriteLine(myUA.list(1)) 当我调用add方法时,我可以看到它正试图将值test123分配

我有一个非常简单的C#类:

在页面加载事件的my default.aspx.cs中,我试图调用list方法:

protected void Page_Load(object sender, EventArgs e)
{
    pillbox.userAccount myUA = new pillbox.userAccount();
    myUA.add();
//Console.WriteLine(myUA.list(1))

当我调用add方法时,我可以看到它正试图将值test123分配给属性,但我得到以下消息:

应用程序代码.1zm0trtk.dll中发生“System.StackOverflowException”类型的未处理异常


你知道我做错了什么吗?

你需要设置私人支持字段,而不是属性。否则,您将进入无限递归,因为您一直在自己身上调用set

    private int _userId;
    private string _userName;

    public int userId
    {
        get { return _userId; }
        set { _userId = value; }
    }
    public string userName
    {
        get { return _userName; }
        set { _userName = value; }
    }
在您的情况下,您可以只使用自动实现的属性(我更改了大小写以符合准则):


这是因为userName调用自己。您可能打算分配字段:

这一行是错误的:

set { userName = value; }
你的意思是写:

set { _userName = value; }

问题在于您定义属性的方式

您试图在setter中引用要为其赋值的属性 这将导致infinte递归(具体来说,此行将触发它
newUser.userName=“test123”

将其更改为:

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

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

如果你重新编写你的二传手,很容易看到发生了什么。属性上的
get
set
实际上被编译为方法(
PropType get\u PropName()
void set\u PropName(PropType value)
),对属性的任何引用都被编译为对适当方法的调用。所以这个代码:

int i = myObj.MyIntProp;
myObj.MyIntProp = 6;
编译成

int i = myObj.get_MyIntProp();
myObj.set_MyIntProp(6);
public void set_username(string value)
{
    set_username(value);
}
那你的二传手呢

set
{
    username = value;
}
实际上编译成

int i = myObj.get_MyIntProp();
myObj.set_MyIntProp(6);
public void set_username(string value)
{
    set_username(value);
}

现在堆栈溢出的原因很明显。

@driis是的,我知道,当三个答案都正确时,仍然很奇怪
public void set_username(string value)
{
    set_username(value);
}