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
204 views
in Technique[技术] by (71.8m points)

c# - Within the Containing Class, Use Property or Field?

Is it good practice to use the private field, or the property, when writing code in the class that contains them?

For example, if I have this field/property pair, classes outside this class must use the property. What about code inside the class? Should it use the private field, or should it also go through the property?

private string _foo;

protected string Foo
{
    get { return this._foo; }
}

private void SomeMethod()
{
  string dummyVariable = "snuh" + this._foo;  // So, this...
  string dummyVariable = "snuh" + this.Foo;  // ... or this?
}

One advantage of using the property here, is if there is any logic in the getter, it will still get executed. I'm curious to know if there is a best-practice policy to follow here.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When using Auto-Implemented properties, you don't have a choice - you must use the property, as you don't have any access to the generated field.

If you property is not simple and does some extra work (validation, firing events etc...), you should call the property in order to centralize access and logic.

If you have any other properties (meaning a simple property with no logic and a backing field) I would ask why are they not one of the above...

With the example you have give, it makes little difference - it is more important to be consistent with how you use these and really boils down to personal aesthetics and coding style.


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

...