C# 发生类型为“System.StackOverflowException”的未处理异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10018356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:09:26  来源:igfitidea点击:

An unhandled exception of type 'System.StackOverflowException' occurred

c#.netstack-overflowgetter-setter

提问by markzzz

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

采纳答案by Oded

You have an infinite loop here:

你在这里有一个无限循环:

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

The moment you refer to Titoloin 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.

Titolo在代码中引用的那一刻,getter 或 setter 调用调用 getter 的 getter,调用 getter 的 getter 调用调用 getter 的 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; }
}

回答by Albin Sunnanbo

Change to

改成

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

    public string Titolo
    {
        get;
        set;
    }
}

回答by user7116

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

你有一个自我参照的 setter。您可能打算使用自动属性:

public string Titolo
{
    get;
    set;
}