Use of get set in c,

Source: Internet
Author: User

Use of get set in c,

When I learned c # in the early stage, I often encountered the following statements:

Public string StudentName

{

Get {return stuName ;}

Set {stuName = value ;}

}

I didn't quite understand why? After learning c #, I cannot make a summary of it. Today I read Visual c #. net Programming Tutorial, this book, summed up well, take a note: In many object-oriented programming languages, attributes {Student stu = new Student (); Console. write (stu. studentName); Console. readKey ();}}}

The code above defines a property, StudentName, which contains get accessors and set accessors. The attribute StudentName encapsulates the stuName field in the Student class. If the field is not added with an access control character, it is set to private by default and cannot be accessed directly by the outside world, currently, the stuName field can be freely accessed through the StudentNamee attribute.

 

The get and set attributes are a combination of executable program statements and have behavior characteristics. When using properties with get accessors and set accessors, they are like using fields, that is, data can be accepted as the left value and output as the right value. The system automatically selects whether to call get or set according to the position where the attribute appears in the statement.

 

Read/write control of attributes

Only one get and set can be used in the attribute. If only get is used but no set is used, this attribute can only be read and cannot be written. If only set is used and no get is used, this attribute is only written, not readable.

Complete more functions in properties

Since get and set are programs, you can certainly do more. A reasonable division of labor is:Design fieldIt is to facilitate the use of internal methods and try to be isolated from the outside world;Design attributesIt is convenient for the outside world to use, but data that is not known to the outside world will not be provided.

 

Details: 

 

SetAccessors and responsesVoidThe method is similar. It is calledValueIs an implicit parameter of the property type. In the following example,SetAccessors addedNameAttribute:

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

When assigning values to attributes, use a parameter that provides new values to callSetAccessors. For example:

e1.Name = "Joe";   // The set accessor is invoked here

InSetUse the implicit parameter name (Value) Is incorrect.

Remarks

Attributes are classified according to the accessors used as follows:

  • OnlyGetThe accessors are called read-only attributes. The read-only attribute cannot be assigned a value.
  • OnlySetThe accessors are called write-only attributes.You cannot reference a property other than the target of the value assignment.
  • WithGetAndSetThe accessors are read/write attributes.

In the attribute declaration,GetAndSetAll accessors must be declared within the attribute body.

UseGetChanging the object status in the accessors is a wrong programming style. For examplenumberField has the side effect of changing the object status.

public int Number {   get   {      return number++;   // Don't do this   }}

You can setGetAccessors are used to return the field value or calculate the field value and return it. For example:

public string Name {   get    {      return name != null ? name : "NA";   }}

In the above Code segment, if notNameAttribute value, which returns the valueNA.

Example 1
This example shows how to access the hidden attributes of another attribute with the same name in the base class.
// Property_hiding.cs
// Property hiding
Using System;
Public class BaseClass
{
Private string name;
Public string Name
{
Get
{
Return name;
}
Set
{
Name = value;
}
}
}

Public class DerivedClass: BaseClass
{
Private string name;
Public new string Name // Notice the use of the new modifier
{
Get
{
Return name;
}
Set
{
Name = value;
}
}
}

Public class MainClass
{
Public static void Main ()
{
DerivedClass d1 = new DerivedClass ();
D1.Name = "John"; // Derived class property
Console. WriteLine ("Name in the derived class is: {0}", d1.Name );
(BaseClass) d1). Name = "Mary"; // Base class property
Console. WriteLine ("Name in the base class is: {0 }",
(BaseClass) d1). Name );
}
}
Output
Name in the derived class is: John
Name in the base class is: Mary
The focus shown in the preceding example is as follows:
The property Name in the derived class hides the property Name in the base class. In this case, the attribute Declaration of the derived class uses the new modifier:
Public new string Name
{
...
The conversion (BaseClass) is used to access the hidden attributes in the base class:
(BaseClass) d1). Name = "Mary ";

 

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------------

Define an attribute in the class
Public class Student
{
Private string name
Public string Name
{
Set {name = value;} // here is the value assigned to the private property name
Get {return name;} // retrieve the value of the private property name
}
}
C # when defining a classObject EncapsulationSo that the outside world cannot access this attribute.If the set part is removed from the above Code, only the value of name can be read from the outside world. If the get part is removed, only the value of name can be assigned.In this way, you can control the externalAccess permissionIs written as follows:A feature of C #.

Of course, you can also create functions to assign values and values to the name, but this is quite troublesome.


The difference between attributes and common variables is that common variables are what is stored in the room. the attribute is to put a hacker at the door of the house, and you take things and put things before him.

This publisher is the property accesser, get is the get, set is the set. It is up to you to decide how to put it, although you think it is just like directly put it.
Get set is an external interface. Generally, to access member data in an instance, the access method of this Member Data is PUBLIC. Now C # is very advanced. GET is GET, SET is SET, however, it provides a high degree of shrinkage. You can SET access permissions for GET and SET separately. For example, you can only read or write data for a member, or only access data from a derived class... In the past, there were no attribute accessors and private member data needs to be called through functions. The attribute provides an efficient access mode and simple writing.
It's for security ~~ 
The field is the specific data you want to operate on, so its value cannot be wrong, but you cannot avoid user mistakes ~~ 
Attribute is used to assign values to fields for security purposes, because in set, you can verify data security,
Get is simpler. After the data is verified, the value is given to the field, so get is required.
Set indicates "set" in Chinese ";
The Chinese meaning of get is "get ";

Supplement:

Get and set are automatically called at the corresponding time.
It is mainly used to hide the data structure in the program.
Get is the value of this attribute,
Set sets the value of this attribute.
There is a special variable value when using set.
Is the attribute value.

ValueImplicit parameters are used to set accessors and add or remove event handlers.

Set attributes of a class
For example, use the class name. Attribute = "" to assign a value to set.
Variable = Class Name. Attribute Value get Function

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.