Properties vs Public member variables [duplicate]

梦想与她 提交于 2019-12-05 19:32:39

问题


Possible Duplicate:
What is the difference between a field and a property in C#

I'm a beginning programmer and I've read all about class properties. Books state that properties allow you to indirectly access member variables. Ok, so what makes it any different than just making the field public and accessing it directly?

Here's a quote from Learning C# 3.0 by Jesse Liberty:

For example, you might want external classes to be able to read a value, but not change it; or you might want to write some code so that the internal field can accept only values in a certain range. If you grant external classes free access to your member fields, you can’t control any of that.

I don't understand what he is saying here. Can someone further explain this or give an example of why I would want to use a property over making the field public. As I understand it now they would both accomplish the same exact thing...so I'm obviously missing something here.


回答1:


Properties can have side-effects, They provide syntactic sugar around 'getter' and 'setter' methods.

public class MyClass {

   int sizeValue = 0;

   public int Size {
      get {
         return sizeValue;
      }
      set {
         if ( value < 10 ) throw new Exception("Size too small");
         sizeValue = value;
      }
   }
}

Properties can also have different levels of protection for get and set, you cannot do that with fields.

public class MyOtherClass {

   // only this object can set this.
   public int Level {
      get; private set; 
   }

   // only things in the same assembly can set this.
   public string Name {
      get; internal set;
   }
}



回答2:


He's saying that properties can provide a getter but not a setter, therefore making them read-only (for example)

Properties are just syntactic sugar for a method e.g.

public int SomeProperty { get; set; }

is just sugar for

private int _someProperty;

public int SomeProperty_get() 
{
   return _someProperty;
}

public void SomeProperty_set(int value) 
{
   _someProperty = value;
}

This means that property setters/getters can apply logic that a mere public field can't

Edit: I'm not exactly sure what field names the CLR gives the backing fields for auto-properties - it's just an example :)

Edit2:

An example of a read only property:

public int SomeProperty { get; }

and finally a public read - private write (for autoproperties)

public int SomeProperty { get; private set; }

Really useful when you can't be bothered to type a backing field in :)

Just remember, if there is a possibility that you wish to apply logic to a member, then a property is the way to go. This is the way a lot of frameworks work (e.g. tracking 'dirty' objects by using a property to tell some sort of object manager that something has changed, this would not be possible using a public field)




回答3:


The other answers provided so far provide details of the advantages of accessor/mutator logic, but all seem to miss out on the ideological point about object encapsulation.

You see, class member fields are an implementation detail. If you have a class that represents a collection, for example, then you could implement it as a linked list (and expose the root-node via a public field) or you could implement it as a resizable array and expose the index0 member.

The problem with revealing implementation details is that you lose any kind of defined interface between your class and its consumers. By ensuring all operations are done via defined methods (controlled by the class itself) you make it easier to work with and provide for a long-term viewpoint. For example, you are far more easily able to convert your collection implementation from one type (the linked-list) to another (the array) without breaking any contracts with your class' consumers.

Don't worry about any performance impact of trivial accessor/mutator methods: the JIT compiler will inline the property methods. If you'll run some benchmarks you'll see the performance of properties vs fields is identical.




回答4:


There are a number of important differences between "properties" and "member access".

The most significant is that you can, through a property, make a member read-only (you can access the state, but you cannot change it). Just like "getter()" and "setter()" methods in Java.

You can also return a computed value from a property (generate a value "on-the-fly", as though it were a variable).




回答5:


Properties can be configured so that:

they are read-only, Public MyProp {get;}

they are write-only Public MyProp {set;}

they are readable by external objects, but can only be set by the class's internals

Public MyProp {get; private set;}

As others have posted, you can also put logic into your getters and setters. For example before allowing the property to bet set to a new value, you can check that the value is acceptable.

You cannot do any of that with a public field.

Basically, a public field is the dumbest sort of property that you can have. Given that .Net now allows autobacking fields for your properties. There is no good reason to use public fields any longer.




回答6:


If you have Public Int MyAge I can set it to -200 or 20,000 and there is nothing you can do about it.

If you use a property you can check that age is between 0 and 150, for example.

Edit: as per IanNorton's example (man, that was fast)



来源:https://stackoverflow.com/questions/11874391/properties-vs-public-member-variables

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