c# - 为什么这段代码会抛出 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;
}
}
}
解决方案
那是因为你在你的吸气剂中调用你的财产。您可以做两件事:为您的班级添加一个字段/成员:
class Test
{
private string company;
public string Company
{
get
{
return company;
}
set
{
company = value;
}
}
}
或将其更改为
public string Company{get; set;}
推荐阅读
- python - 为什么 getoldtweets3 库提供 404 错误?
- powerbi - Power bi 表中的超链接操作
- reactjs - 来自 localStorage 的 react-native-webview getItem()
- python - 调用类和函数时Python Selenium中xpath中的变量
- docker - Docker:设置超时并使用错误代码退出
- go - 如何在函数中将字符串值转换为自定义类型
- c++ - 如何从元素中获取孩子?
- html - 在 react-bootstrap 中将变量传递给页面
- javascript - useRef 还是 DOM api?
- php - 如何通过 user_id Laravel 更改数组结构