How to avoid stack overflow errors when defining set accessor in C#(在 C# 中定义 set 访问器时如何避免堆栈溢出错误)
问题描述
stackoverflow 的人.我是 c# 的新手,这是我第一次无法找到我的一个基本问题的答案.谁能帮帮我?!我正在尝试为公共实例字段定义集合逻辑.
People of stackoverflow. I am new to c# and this is the first time I have not been able to find an answer to one of my elementary questions. Who can help me?!I am trying to define set logic for a public instance field.
运行完美,
公共字符串标题{get;设置;}
public string Headline {get; set;}
这会导致堆栈溢出
公共字符串标题
{得到{返回标题;}放{标题=价值;}}
public string Headline
{ get { return Headline; } set { Headline = value; } }
推荐答案
你在递归调用getter和setter(无限调用自己),不可避免地导致堆栈溢出.
You're calling the getter and setter recursively (calling themselves infinitely), inevitably causing a stack overflow.
这就是你的意思:
private string headline;
public string Headline
{
get { return headline; }
set { headline = value; }
}
请注意,如果您不打算引入任何进一步的 get/set 逻辑,则这是不必要的,因为这正是您的第一个示例在幕后所做的.
Note that this is unnecessary if you don't plan to introduce any further get/set logic, as this is exactly what your first example does behind the scenes.
在学习 c# 中的属性时,最好不要将它们视为数据,而是将其视为具有以下签名的一对方法:
When learning about properties in c#, it helps to think of them not as data, but as a pair of methods with the following signatures:
public string get_Headline() { ... }
public void set_Headline(string value) { ... }
事实上,这正是编译器定义它们的方式.
In fact, this is exactly how the compiler defines them.
现在很容易看出您的初始代码会递归调用 set_Headline
.
Now it's easy to see that your initial code would call set_Headline
recursively.
这篇关于在 C# 中定义 set 访问器时如何避免堆栈溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中定义 set 访问器时如何避免堆栈溢出错误
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01