首页 > 解决方案 > 为什么这段代码会抛出 StackOverFlow 异常?

问题描述

我正在学习 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;
        }
    }
}

标签: c#exceptionstack-overflowgetter-setter

解决方案


那是因为你在你的吸气剂中调用你的财产。您可以做两件事:为您的班级添加一个字段/成员:

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

或将其更改为

public string Company{get; set;}

推荐阅读