An unhandled exception of type 'System.StackOv

2020-02-11 03:19发布

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

3条回答
来,给爷笑一个
2楼-- · 2020-02-11 03:48

Change to

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

    public string Titolo
    {
        get;
        set;
    }
}
查看更多
混吃等死
3楼-- · 2020-02-11 03:53

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

public string Titolo
{
    get;
    set;
}
查看更多
我只想做你的唯一
4楼-- · 2020-02-11 03:55

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; }
}
查看更多
登录 后发表回答