在C#中定义set访问器时如何避免堆栈溢出错误 [英] How to avoid stack overflow errors when defining set accessor in C#
问题描述
完美运行,
public string Headline {get;设置;}
这导致堆栈溢出
公共字符串标题
{
获取
{
return标题;
}
set
{
Headline = value;
(无限地调用自己),不可避免地会导致堆栈溢出。
当然这就是你的意思:
私人字符串标题;
public string Headline
{
get {return headline; }
set {headline = value; }
}
请注意,如果您不打算进一步介绍获取/设置逻辑,因为这正是你在后台执行的第一个例子。
当学习c#中的属性时,有助于将它们视为数据,但作为一对具有以下签名的方法:
public string get_Headline(){...}
public void set_Headline(string value){...}
事实上,这正是编译器定义的他们。
现在很容易看到您的初始代码会递归地调用 set_Headline
。
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.
This runs flawlessly,
public string Headline {get; set;}
This results in stack overflow
public string Headline
{ get { return Headline; } set { Headline = value; } }
You're calling the getter and setter recursively (calling themselves infinitely), inevitably causing a stack overflow.
Surely this is what you mean to be doing:
private string headline;
public string Headline
{
get { return headline; }
set { headline = value; }
}
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.
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.
Now it's easy to see that your initial code would call set_Headline
recursively.
这篇关于在C#中定义set访问器时如何避免堆栈溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!