An unhandled exception of type 'System.StackOverflowException' occurred

孤街浪徒 提交于 2019-11-28 00:21:51

问题


Why this? This is my code :

public class KPage
{
    public KPage()
    {
       this.Titolo = "example";
    }

    public string Titolo
    {
        get { return Titolo; }
        set { Titolo = value; }
    }
}

I set data by the constructor. So, I'd like to do somethings like

KPage page = new KPage();
Response.Write(page.Titolo);

but I get that error on :

set { Titolo = value; }

回答1:


You have an infinite loop here:

public string Titolo
{
    get { return Titolo; }
    set { Titolo = value; }
}

The moment you refer to Titolo in your code, the getter or setter call the getter which calls the getter which calls the getter which calls the getter which calls the getter... Bam - StackOverflowException.

Either use a backing field or use auto implemented properties:

public string Titolo
{
    get;
    set;
}

Or:

private string titolo;
public string Titolo
{
    get { return titolo; }
    set { titolo = value; }
}



回答2:


You have a self-referential setter. You probably meant to use auto-properties:

public string Titolo
{
    get;
    set;
}



回答3:


Change to

public class KPage
{
    public KPage()
    {
       this.Titolo = "example";
    }

    public string Titolo
    {
        get;
        set;
    }
}


来源:https://stackoverflow.com/questions/10018356/an-unhandled-exception-of-type-system-stackoverflowexception-occurred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!