Each review has a deeper understanding: C # attributes, fields, and variables

Source: Internet
Author: User

C # Fields refer to private fields (variables)
Class
{
Int I;

Public int I
{
Get {....}
Set {....}
}
}

Where, I is a field, I is a property,
A field belongs to a class and is defined in the class (Note: it is a class, not a method or attribute in the class)
This class can be used
This. Field name access
All attributes and methods in this class can be accessed.
That is to say, its scope is the entire class.

Local variables belong to a function or statement block.
Its scope is from definition to exit statement block.

Process of variables, fields, fields, attributes, and attributes in C #

In C:

Field: indicates the variable associated with the object or class, whether it is public or not. (Similar to the field)
Field: indicates the variable associated with the object or class. In general, modifier is a public member variable called a field, while private is more suitable for local variables. (Similar to the domain)
Attribute: represents the natural extension of the domain or field, making it easy to access private members on the basis of ensuring encapsulation.

Domain

Fields represent variables associated with objects or classes. The declaration format is as follows:

Attributes field-modifiers Type Variable-declarators;

Field-modifiers can be: new, public, protected, internal, Private, static, and readonly. In fact, the domain is equivalent to a simple member variable in C ++. In the following code, Class A contains three fields: Public X and Y, and private Z.
Class
{
Public int X;
Public String y;
Private float Z;
}

Field

Fields are variables associated with objects or classes.
When a field Declaration contains a static modifier, the field introduced by this declaration is a static field ). It identifies only one storage location. No matter how many class instances are created, the static field will only have one copy.
When a field declaration does not contain a static modifier, the field introduced by this declaration is the instance field ). Each instance of the class contains a single copy of all instance fields of the class.
In the following example, each instance of the color class has different copies of the R, G, and B instance fields, but black, white, red, static fields such as green and blue have only one copy:
Public class color
{
Public static readonly color black = new color (0, 0, 0 );
Public static readonly color white = new color (255,255,255 );
Public static readonly color red = new color (255, 0, 0 );
Public static readonly color green = new color (0,255, 0 );
Public static readonly color blue = new color (0, 0,255 );

Private byte R, G, B;

Public color (byte R, byte g, byte B ){
This. r = R;
This. G = g;
This. B = B;
}
}
As shown in the example, read-only fields are declared through the readonly modifier. The value assigned to the readonly field can only appear as part of the Declaration, or in the instance constructor or static constructor of the same type.

Attribute

For Class encapsulation, the field is generally set to private, and the attribute is set to public to operate the field.

Property is a natural extension of fields. Both are named members of the associated type, and the syntax for accessing fields and properties is the same. However, different attributes and fields do not represent the storage location. On the contrary, there are accessors for attributes, which specify the statements to be executed when their values are read or written.

The attribute declaration is similar to a field. The difference is that the attribute declaration ends with the get accessor and/or set accessors between the delimiters {}, rather than semicolons. The attributes that contain both get accessors and set accessors are called read-write properties ). Only the get accessors are read-only properties ). The property with only the set accessors is called the write-only property ).

The get accessor is equivalent to a non-parameter method with a returned value of the attribute type. In addition to being the target of the value assignment, when an attribute is referenced in an expression, the get accessor of this attribute is called to calculate the value of this attribute.

Set accessors are equivalent to a method with a single parameter named value and no return type. When an attribute is referenced as the target of the value assignment or as the operand of ++ or -- operator, the set accesser is called and the passed independent variable provides a new value.

The List class declares two attributes: Count and capacity, which are read-only and write-only. The following is an example of using these attributes:
List names = new list ();
Names. capacity = 100; // call the set accessors.
Int I = names. Count; // call the get accessors.
Int J = names. capacity; // call the get accessors.

Similar to fields and methods, C # supports both instance attributes and static attributes. Static attributes are declared with static modifiers, while instance attributes do not.
Attribute accessors can be virtual. When the attribute Declaration contains virtual, abstract, and override modifiers, they are applied to the attribute accessors.

Content from msdn:

Attributes and fields
Attributes and fields can be stored and retrieved in objects. Their similarity makes it difficult to determine which programming option is better under a given circumstances.
Use the attribute process in the following situations:
1. When you need to control the time and method of setting or retrieving values.
2. When the attribute has a well-defined set of values that need to be verified.
3. The setting value causes some obvious changes in the object State (such as the isvisible attribute ).
4. setting properties will cause changes to the values of other internal variables or other properties.
5. You must perform a set of steps before setting or retrieving attributes.
Use fields in the following scenarios:
1. When the value is of the self-verification type. For example, if a value other than true or false is assigned to a Boolean variable, an error or automatic data conversion occurs.
2. Any value within the range supported by the data type is valid. This is the case for many single or double attributes.
3. the attribute is of the string data type and has no constraints on the size or value of the string.

Differences between attributes and variables in Visual Basic (the same should be true in C)

Both variables and attributes indicate accessible values. However, the storage and implementation are different.
Variable
The variable directly corresponds to the memory location. You can use a single declaration statement to define variables. A variable can be a local variable, which is defined in the process and can only be used in the process. It can also be a member variable, which is defined in a module, class, or structure, but it is not defined in any process. A member variable is also called a field ".
Attribute
An attribute is a data element defined in a module, class, or structure. Use the code block between the property and end property statements to define the property. This code block contains a get Process T or a set process, or both. These two processes are called "attribute process" or "attribute accessors ". In addition to retrieving or storing attribute values, they can also perform custom operations, such as updating access counters.
Differences
The following table lists some important differences between variables and attributes.
Variance point variable attributes
Declare a series of statements in a single statement Block
Code execution (attribute process) for a single storage location)
Storage directly associated with variable values usually contains internal storage; outside the attribute inclusion class or module, the values of these inner storage unavailability attributes may or may not be used as a storage element (see (1 ))

There must be at least one process for executable code
Read/write or read-only read/write, read-only or write-only
A custom operation cannot be executed as partial setting or retrieving attribute values.
Note: (1) different from the variable, the attribute value may not directly correspond to a single storage item. For convenience or security, the storage may be split into several blocks, or values may be stored in encrypted format. In these cases, the get process will compile these blocks or decrypt the stored values, and then the set process will encrypt the new values or split them into various components of the storage. The attribute value can be temporary, for example, a certain time in a day. In this case, each time you access this attribute, the get process will calculate this attribute in time.

Differences between classes and modules
The main difference between a class and a module is that a class can be instantiated as an object, but a standard module cannot.

Part 2

Example of variables:
String A = "";
Fields and attributes are relative to the class. In the class, data members are called fields, which are usually defined as seemingly fields. access modifier private is added, and attributes are encapsulated for private fields, for external access to the class, only attributes can be seen, but private fields cannot be seen. Access to attributes is an operation on private members of the class!
For example:
Class
{
String _ strname

Public String strname
{
Get {

Return this. _ strname;
}
Set {
This. _ strname = value;
}
}
}
In this way, you can use strname to access the private field _ strname of category!

Part 3

First, we need to know what fields are.
How can we record some information?
For example, if you want to match a prescription, it must be described by others.
Danggui, 4 yuan, fat sea, 1 yuan ......
In the computer world, we need to record this information. At this time, we need fields, that is, the variables we declare.
Someone has to ask again. Now that variables are available, can I declare them as public and directly use them (instance. Variable?
Why are there so many additional attributes?
This is because some variables we don't want to expose to others. The variables you declare may be used by others. If others have the permission to read and write this field casually, it is difficult to ensure the correctness and security of the field.
Therefore, you can control the read and write permissions on the field in the attribute (get is read, set is write) to talk about its correctness.
If you want to record a student's mathematical score (assuming the full score is 100), someone sets the field for recording the mathematical score to 150 or-1, it is obviously wrong. We can control the attribute to reduce this error!

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.