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
Program The design tutorial is a good summary. Take the following notes:
In many object-oriented programming languages, attributes refer to the features and states of objects, specifically the data members of objects. A programmer can specify whether a data member can be directly accessed by the outside world. If the data member is specified as public, the outside world can access the member by using "Object Name. Public Data member name. C # is a fully object-oriented language. C # advocates a new way to better encapsulate and protect data members and provide more effective access forms to the outside world. In C #, "attributes" are used to achieve this goal, and those data members are called "fields" or "fields" in C ".
attribute definition and usage
attributes are composed of two parts: attribute header and storage. Memory is divided into get accessors and set accessors. The general form of declared attributes is:
modifier type attribute name
{< br> Get/get accessors
{...}
set // set accessors
{...}
}< br> the modifier of the attribute can be any access controller or static. Get and set are specific methods. Get is used to read data from objects, while set is used to write data to fields. When external data is written to fields, C # Use value to represent the input data. value can be a quasi-Keyword, for example:
set {afield = value ;}< br> The following is a simple example, demonstrate the basic form and usage of attributes:
using system;
using system. collections. generic;
using system. text;
usage of the namespace attribute
{< br> public class student
{< br> private string stuname = "A Hui Nan ";
Public String studentname
{< br> get {return stuname ;}< br> set {stuname = value ;}
}< BR >}< br> class Program
{< br> static void main (string [] ARGs)
{< br> Student Stu = new student ();
console. write (Stu. studentname);
console. readkey ();
}< BR >}
AboveCodeDefines a property of studentname, which includes 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, now, the stuname field can be freely accessed through the studentname 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.