Correct use of fields that are encapsulated in properties inside a class

孤街浪徒 提交于 2020-01-04 15:58:13

问题


Which scenario should I use for changing private fields inside class methods/properties:

public class Example
{
 private int intVar = 0;
 private string stringVar = string.Empty;

 public int IntVar
 {
  get { return this.intvar; }
  set { this.intvar = value; }
 }

 public string StringVar 
 {
  get { return this.stringVar ; }
  set { this.stringVar = value; }
 }

 private void SomeMethod()
 {
  //change fields in this way:
  this.intVar = 50;
  this.stringVar = "changed";
  //or that way(through properties):
  this.IntVar = 50;
  this.StringVar = "changed";
 }
}

Maybe in this example it makes no difference, but what if someone add extra code to properties, and changing fields through properties will change some other things?

Can you say which way is better, or it really makes no difference?

I know that since C# 3.0 I can write auto-implemented properties, but this is C# 2.0.


回答1:


I'd say using a property is usually better. If the getters and setters are simple, they might get inlined by the jitter at runtime anyway. And as you said, maybe other changes will be made to the property code.

A common change is adding change notifications by implementing INotifyPropertyChanged. Listeners would not get notified if you set the fields directly, then.

I prefer my classes to use their own public interface rather than internals. An exception for me is when i explicitly do not want any of the side effects. That is rarely the case though.




回答2:


From my experience, always use properties and do not try to access directly at your var. If, in the future, someone add code to the property accessors, is its responsability to check the side effects of its changes.

In that scenario, you will facilitate the testing work. The change implementor needs to check only on the public names and not the internal vars.




回答3:


If you do some sort of validation, for example mark an Example object as invalid when the intVar exceeds the 100 value, then you should use the Properties.

public int IntVar
 {
  get { return this.intvar; }
  set 
      { 
         if ( value > 100)
            // handle this corner case
         else      
           this.intvar = value; 
      }
 }

Let's say your private method does some calculations

private void SomeMethod()
 {
   int result = ...;
   IntVar = result;
 }

When SomeMethod is called is better to use here the property, so the property would handle the validation, since the field can't do this.




回答4:


It doesn't make any difference and is a personal preferences.
I prefer to use the properties.



来源:https://stackoverflow.com/questions/10243851/correct-use-of-fields-that-are-encapsulated-in-properties-inside-a-class

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