How to avoid stack overflow errors when defining set accessor in C#

旧时模样 提交于 2019-12-19 19:54:44

问题


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; } }


回答1:


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.




回答2:


You need a backing field if you are trying to use set and get with your property.

private string _headline; //backing field.

public string Headline
{
    get { return _headline; }
    set { _headline = value; }
} 

In your current code, you are trying to set your property recursively, and thus resulting in stackoverflow exception




回答3:


Because you're returning the same thing recursively.

private string _headLine

public string Headline
{ 
   get 
   { return _headline; } 
   set 
   { _headline = value; } 
}



回答4:


In this case instead of generating a new variable like the rest of the answers are saying. You can simply just write.

public string Headline { get; set;}

This will allow anyone to retrieve this variable which you could re write as

public string Headline;

If you want the setting to be private you can say.

public string Headline { get; private set; }

I like it this way better because this way you don't have to allocate a new variable and the readability of the code greatly increases :)



来源:https://stackoverflow.com/questions/20197716/how-to-avoid-stack-overflow-errors-when-defining-set-accessor-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!