C # Property Accessors

Source: Internet
Author: User


The accessor of a property contains an executable statement about the GET or set property. An accessor declaration can contain either a get accessor or a set accessor, or both. The declaration takes one of the following forms:
get {}
set {}

Get accessor
The get accessor body is similar to the method body. It must return the value of the property type. Executing a get accessor is equivalent to reading the value of a field. The following is a get accessor that returns the value of the private field name:

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

private string name;   The name Fieldpublic string name//The name property{get {return name; }}

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

When a property is referenced, the get accessor is called to read the value of the property unless the property is an assignment target. For example:

Employee e1 = new Employee ();
...
Console.Write (E1. Name); The get accessor is invoked here
The get accessor must be terminated in a return or throw statement, and the control cannot exceed the accessor body.

Set accessor
The set accessor is similar to the method that returns void. It uses an implicit argument called value, and the type of this parameter is the type of the property. In the following example, the set accessor is added to the Name property:

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

public string name{get {return Name;   } set {name = value; }}

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

When you assign a value to a property, the operation invokes the set accessor. For example:

E1. Name = "Joe"; The set accessor is invoked here
It is an error to use an implicit parameter name (value) for a local variable declaration in a set accessor.

Note
Properties are categorized according to the accessors used, as follows:
Properties with only a get accessor are called read-only properties. Cannot assign a value to a read-only property.
A property with only a set accessor is called a write-only property. A write-only property cannot be referenced except as the target of an assignment.
Properties with both get and set accessors are read-write properties.
In a property declaration, both get and set accessors must be declared inside the property body.
Using the get accessor to change the state of an object is a bad programming style.

====

Let's use the following example to understand what an accessor is:

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

 using System;  namespace AccessorEG {           public class Student     {                   //  Private Fields  private  field         private int _age;                    //  Public Properties   public property         public int age          {                          get { return  _age; }                          set { _age = value; }          }     }            class Program     {                   static void main (string[]  args)          {              student stu = new student ();              stu. age = 10;                            //  using the Modify               console.writeline (Stu. AgE.tostring ());  //  use Read                      console.readkey ();                       //  output  10                       }     } }

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

Well understood, the accessor refers to the object type member to the outside interface, is the object type member and the outside world to carry on the information interaction Bridge, has the accessor, the outside world can read, writes the correspondence operation to the object member.

So, what members can have accessors? Fields and events that are not read-only can be declared accessors. Of course, a read-only domain can also provide an externally acquired interface, which is get, but can only be initialized in a declaration or constructor, and it does not support providing a set method.

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

 using System;  namespace AccessorEG {           public class Student     {                   //  Private Fields  private  field         private readonly int _age =  10;                    //  Public Properties  public property          public int Age         {                   get { return  _age; }         }     }            class program     {                  static void main (string[]  args)          {              student stu = new student ();              console.writeline (Stu. Age.tostring ());  //  use Read                      console.readkey ();                       //  output  10                    }     } }

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

The value of the read-only field in the code above is already assigned at the time of declaration, and it does not provide a set method for the accessor of the exposed property, otherwise it cannot be compiled, but it can be obtained by the outside world.

About the accessors of a field we also have to say something that is commonly written as follows:

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

using system;  namespace accessoreg {           public class Student     {                    #region   Full access           //  private Field          private  int _age;        //  public properties corresponding to the _age, including the set and Get methods                    public  int Age         {                            get { return _age; }                           set { _age =  value; }         }           //  if you installed the.    NET3.0, then you can use the automatic properties, then, the above code can be the following instead of    //  enter  prop  combo under vs.net tab, the compiler will automatically help you generate automatic properties    // public int Age { get; set; }           #endregion  //  Full access rights           # region  read-only properties                    private string _name;                    public string Name          {          &nBsp;              get { return  _name; }         }           //  equivalent to    // public string Name { private  set; get; }          #endregion             #region   Write-only properties                    private bool _sex;                    public bool  Sex         {                        set {  _sex = value; }         }                   //  equivalent to    // public  bool sex { set; private get; }           #endregion       }            class Program     {                   static void main (String[] args)          {              student stu = new student ();              stu. Age = 18;           &nbSp;              // stu. name =  "Johness";  exception, compile error because the property is read-only     // console.writeline (Stu. Sex.tostring ());  exception, compile error because this property is only written               console.writeline (Stu. Age.tostring ());  //  use Read                      console.readkey ();              //  Output  18                   }     } }

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

Read-only, write-only in the above example is valid only for the outside world, if you display the owner of the accessor, the private field of the class. Then inside the class, you can still conveniently use the private fields you define to read and write, so I recommend that friends define fields and their accessors to use. NET2.0 syntax without a new syntax of 3.0 (automatic attributes). Of course, the use of accessors can also be better for validating data validity:

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" Border:none; "/>

 using System;  namespace AccessorEG {           public class Student     {                   //  Private Fields           private int _age;  //  public properties corresponding to the _age, including the set and Get methods                    public int age         {                            get { return _age; } //  using accessors to verify the age of input     //   If the input value is less than 0 or greater than    //  can be assigned the default value of 18 or not action               set              {                                      if   (value >= 0 && value <= 100)                      _age =  value;   //  If the data is not valid, you can annotate the following:                     else                     _age = 18;              }          }  &nbsP;   }           class program      {                   static void main (String[] args)           {             student  stu = new student ();              stu. age = -2;   //  Assignment Invalid value                                     console.writeline (Stu. Age.tostring ());               Console.readkey ();    //  output  18                  }      } }


C # Property Accessors

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.