为什么此代码会引发StackOverFlow异常?

时间:2020-07-25 22:27:47

标签: c# exception stack-overflow getter-setter

我正在学习C#中的getter和setter方法,并遇到了这段代码。我了解C#上下文在这里出了什么问题。它没有编译时错误,但是会抛出运行时异常。有人能解释导致调用堆栈溢出的原因吗?

using System;

class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        Console.WriteLine(test.Company);
    }
}

class Test
{
    public string Company
    {
        get
        {
            return Company;
        }
        set
        {
            Company = value;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

那是因为您在getter中调用属性。 您可以做两件事:向您的班级添加一个字段/成员:

class Test
{
    private string company;   
    public string Company
    {
        get
        {
            return company;
        }
        set
        {
            company = value;
        }
    }
}

或将其更改为

public string Company{get; set;}