The difference between C # property relations, member variables

Field typically use internal class, class attributes generally for external access.

In accordance with the design principles class, fields are private and can only be used inside the class, if it is public, then the outer class who are likely to visit, destructive changes to the field, which we do not want to see , so the field must be private.

So I want to attribute to the field plus a protective sleeve, if you want to read the value of this field, which is taking the property must get {}, if you want to field assignment, property in some taking the set {}, so programmers can increase get {} and set {} are some restrictions, to verify the contents of the assignment, or having a field can only read can not be assigned (to the field of property should have just let it get {}, do not write the set {}) . For external users is only able to use it, it can not control, how to control the operation itself is determined by the class (or is determined by the programmer).

Further, the field value can be used as ref, out parameters, and property can not.

So why not use the class member variables public, and to use the property? Property benefits:

1: The property is read-write with get with the set, after the privatization of variables, is tantamount to protect the field, external only released property. May be provided a read-only,

E.g:

 private int _name

 public int name // define an attribute b
  {   
   GET
   {
    return the _name;
   }
   SET
   {
    the _name = value; // b to assignment
   }

If the name attribute only get here do not set it, just change the function of a read-only function, which for some reading strings, profiles, fixed constants have a good effect.

2: property could do with some rule or check constraint set the data format of the time, these variables can be up normative role, the class is eliminating a lot of trouble

 

Published 224 original articles · won praise 14 · views 40000 +

Guess you like

Origin blog.csdn.net/xulong5000/article/details/105097863