C # Language Series Lectures (7) domains and attributes

Source: Internet
Author: User
● Field, also known as member variable, is divided into instance domain and static domain. Domain access restrictions reflect the encapsulation principles of object-oriented programming;

● There are two functions behind the property: the value assignment function (get) and the value function (SET ).

Domain

Field, also known as member variable, represents the storage location and is an indispensable part of the C # class. The type of the domain can be any data type in C #. However, for reference types other than the string type, some class constructor operations are involved during initialization, the plan will be described in subsequent chapters.

Domains are divided into instance domains and static domains. The instance domain is a specific object and is private to a specific object. Static fields belong to the class and are shared by all objects. C # Strictly stipulate that instance domains can only be obtained through objects, and static domains can only be obtained through classes.

Domain access restrictions reflect the encapsulation principles of object-oriented programming. As mentioned above, there are 5 types of access restriction modifiers in C #, which are applicable to the domain. C # extends the original friend modifier of C ++ with internal. When it is necessary to make some fields of the two classes visible to each other, declare the fields of these classes as internal, and then compile them in a composite body. If you need to be visible to their inherited child classes, declare them as protected internal.

C # introduces the readonly modifier to represent read-only fields, and const to represent unchanged constants. As the name implies, the read-only domain cannot be written, and constant cannot be modified. What is the difference between the two? Read-Only fields can only be assigned values during initialization (Declaration initialization or constructor initialization). Otherwise, the compiler reports an error. The read-only domain can be an instance domain or a static domain. The type of the read-only domain can be any type of the C # language. The const-modified constant must be assigned a value at the same time as it is declared, and the compiler is required to calculate this definite value during compilation. The constant modified by const is a static variable and cannot be obtained by the object. The type of the value modified by const is also limited. It can only be one of the following types (or can be converted to the following types): sbyte, byte, short, ushort, Int, uint, long, ulong, Char, float, double, decimal, bool, String, Enum type, or reference type. It is worth noting that the reference types here, except for the string type, all types (except the value is null) cannot be computed by the compiler during compilation, therefore, the reference type that can be declared as const can only be string or other reference types whose values are null. If you need a const constant, but its type limits that it cannot be computed at compilation, you can declare it as static readonly. The constant modified by const is calculated as a definite value during compilation, and replaced by every place that references the constant, while readonly determines the value at runtime, we don't want to change its value any more, which is the main difference between the two.

Domain Initialization is a special issue in object-oriented programming. C # The Compiler initializes each domain as its default value by default. Simply put, the default value of the numeric type (Enumeration type) is 0 or 0.0, the default value of the character type is '/x0000', and the default value of the boolean type is false, the default value of the reference type is null, and the default value of the structure type is the corresponding default value for all types in it. Although the C # compiler sets the default type for each type, the variable needs to be correctly initialized according to the object-oriented design principle, which is also recommended by C, if the domain is not initialized, the compiler will issue a warning. C # There are two ways to initialize the domain: Initialize the declaration at the same time and initialize the domain in the constructor. As mentioned above, the Declaration initialization of the domain is actually executed by the compiler as a value assignment statement at the beginning of the constructor. Instance variable initialization will be placed in the instance constructor, and static variable initialization will be placed in the static constructor. If a static variable is declared and initialized at the same time, the compiler constructs a static constructor to convert the initialization statement into a value assignment statement. As a constant volume field modified by const, it cannot be regarded as an initialization statement in a strict sense. It can be considered as a macro replacement similar to that in C ++.

Attribute

Attribute can be an innovation of C # language, or not. The reason is that the implementation behind it is actually two functions: the value assignment function (get) and the value function (SET), which can be clearly seen from the intermediate language code generated by it. The reason is that it does implement the special interface of the OO Style Class "attribute" for object-oriented programming at the language level. C # It is not recommended to set the protection level of the domain to public, so that users can perform any operation outside the class-that is too insecure! For all fields that need to be visible outside the class, C # is recommended to use attributes for representation. The attribute does not represent the storage location, which is the fundamental difference between the attribute and the domain. The following is a typical attribute design:

Using system;

Class myclass {

Int integer;

Public int INTEGER {

Get {return integer ;}

Set {INTEGER = value ;}

}

}

Class test {

Public static void main (){

Myclass myobject = new myclass ();

Console. Write (myobject. integer );

Myobject. Integer ++;

Console. Write (myobject. integer );

}

}

As expected, the program outputs "0 1 ". We can see that the attributes provide a friendly access interface for domain members by packaging methods. Here, value is the key word of C #, which is the implicit parameter of the Set function during attribute operations, that is, the right value during attribute write operations.

Attribute provides read-only (get), write-only (SET), read-write (get and set) Three interface operations. These three operations on the domain must be declared under the same attribute, but they cannot be separated.

Of course, attributes are not limited to domain interface operations. The nature of attributes is still a method. You can perform some checks, warnings, and other additional operations according to the program logic when extracting or assigning values to attributes, see the following example:

Class myclass {

Private string name;

Public string name {

Get {return name ;}

Set {

If (value = NULL)

Name = "Microsoft ";

Else

Name = value;

}

}

}

Because of the nature of the attribute method, the attribute also has various methods for modification, and the attribute also has five access modifiers, but the attribute access modifier is usually public, otherwise, the meaning of attributes as the public interface of the class will be lost. Except for special attributes such as method overloading caused by multiple parameters of methods, virtual, sealed, override, and abstract modifiers have the same behavior for attributes as for methods, however, because an attribute is implemented as two methods in essence, some of its behaviors must be noted. See the following example:

Abstract class {

Int y;

Public Virtual int X {

Get {return 0 ;}

}

Public Virtual int y {

Get {return y ;}

Set {Y = value ;}

}

Public abstract int Z {Get; set ;}

}

Class B: {

Int Z;

Public override int X {

Get {return base. x + 1 ;}

}

Public override int y {

Set {base. Y = value <0? 0: value ;}

}

Public override int Z {

Get {return Z ;}

Set {z = value ;}

}

}

This example focuses on some typical behaviors of attributes in the inheritance context. Here, Class A must be declared as abstract because of the existence of abstract attribute Z. In subclass B, the attribute of parent class A is referenced by the base keyword. In Class B, the virtual attribute in Class A can be overwritten only through the set function of Y.

Static attributes, like static methods, can only access static domain variables of the class. As with external methods, external attributes can be declared.

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.