Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

get - How to avoid stack overflow errors when defining set accessor in 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.

This runs flawlessly,

public string Headline {get; set;}

This results in stack overflow

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...