在 C# 中定义 set 访问器时如何避免堆栈溢出错误 [英] How to avoid stack overflow errors when defining set accessor in C#

查看:33
本文介绍了在 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 访问器时如何避免堆栈溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆