C # And. NET3.5 advanced programming (version 4th) Note 5

Source: Internet
Author: User

Chapter 5 define encapsulated class types

This chapter describes the object-oriented functions of c. First, we will introduce how to build a class type, then study the role of encapsulation, then discuss the definition of attributes, fields, and other content, and finally study the role of XML Code Document Syntax.

5.1 class types and their Constructors

Basic concepts of classes:

A class is a custom type consisting of a data field (also called a member variable) and a member (constructor, attribute, method, event, etc.) that operates the data. The field data is used to indicate the "status" of the class instance (also called the object). The object is an instance of a class type that is created using the new keyword. The object must be allocated to the memory using the new keyword. If new is not used, a compiler error is generated when this object is used. For example, for the following sentence:

Car mycar = new car ();

The code in the first half declares a reference (pointer) pointing to a car object that has not been created, but it points to null at this time. After a reference is assigned to an object through new, this reference will point to a valid class instance in the memory.

Note: Only members and member variables can be defined, and operations cannot be performed on members, suchAssign a value againAnd so on. These operations can only be performed in members!

Class constructor:

The object state (represented by member variables) can be assigned values one by one. This is acceptable for a small class. However, if there are many fields, values are assigned one by one each time, is unimaginable. This requires the constructor, which can assign relevant values to the field data of the object before using the object, that is, the initialization operation.

The constructor in C # is a special method that is called indirectly when an object is created using the new keyword. It does not return values (void does not work) and the name is the same as the class name.

C # provides the default constructor. It does not receive parameters. Its function is to ensure that all field data is set to the correct default value when the new object is allocated to the memory. Of course, you can redefine the default constructor (without parameters), or you can define a custom constructor with parameters.

Note: As shown in the previous chapter, the value type also has a default constructor (int, float ...., struct). The default constructor (without parameters) is provided for these types of systems. You cannot explicitly redefine the non-argument constructor, you can customize constructors with parameters.

For reference types, once a user-defined constructor is defined, if the default constructor is not explicitly defined, the default constructor provided by the system will beRemoved and invalidOr the system no longer provides Default constructors. Therefore, if you want to use the default constructor and custom constructor to create an instance, you must explicitly redefine the default constructor.

Note: The default constructor is private. To use the constructor, you need to add other modifiers.

This Keyword:

This keyword is used for the current instance (Object), That is, the current instance. Therefore, this cannot be used at the class level, for example, in a static method.

This keyword has two purposes:

(1) this keyword resolves the Scope Ambiguity generated when the name of the currently passed parameter and the name of the type data field are the same. For example:

Class motorcycle {public string name; // The member variable is named name public void setdrviername (string name) // The input parameter is also called name {name = name; // which value is assigned to this sentence? The intention is to assign the parameter value to the member variable, // However, this statement assigns the parameter value name to the parameter value name. This. name = name; // this is the meaning of assigning the parameter value to the member variable }}

(2) Call the series Constructor

It uses a technology called "Constructor chain" to design classes. When a class contains multiple constructor, and the constructor has redundant code (such as checking and verifying all), which can be used.

Of course, for conventional methods, to prevent redundant code in constructor, you can design a method specifically to constructor calls, but a more concise method is, let a constructor that receives the maximum number of parameters "primary constructor" to implement the necessary verification logic. Other constructors use the this keyword to forward the passed parameters to the primary constructor and provide all required other parameters. this requires the colon operator, for example:

Class motorcycle {public int driverintensity; public string drivername; public motorcycle () {} public motorcycle (int intensity): this (intensity, "") {} public motorcycle (string name ): this (0, name) {} public motorcycle (int intensity, string name) {// related code }}

Here, this represents the called constructor, followed by the parameters of the called constructor.

In this way, we define a class that uses many constructors to create field data (member variables) and various members.

Note: Incorrect calls may lead to an endless loop! For example:

public motorcycle(int intensity):this("") { }public motorcycle(string name):this(0) { } 

The above two constructors call each other. If one of them is called during instantiation, it will lead to an infinite loop structure. I feel that this problem should be prompted during compilation, unfortunately, it is not smart enough to report an endless loop overflow error when it reaches the running stage.

Note: this keyword will reference the current instance of the class. The static member function does not have this.
This keyword can be used to access members from constructors, instance methods, and instance accessors.
It is incorrect to reference this in the variable initial values set for static methods, static property accessors, or field declarations.

Public class MyClass {int a = 0; // int B = this. a; // the initial value of the member variable cannot use thispublic static void RunSnippet () {// public int c = this. a; // static methods cannot use this ;}}

5.2 static keywords

C # classes and structures can be defined by using the static keyword. In this case, these members can only be called at the class level rather than the instance level. In short, the static method is considered to beVery common itemAnd you do not need to create a type instance when calling a member. Although any class or structure can be defined as a static method, they usually appear in the "tool class.

(1) define static methods (and fields)

You only need to add static before the method definition. Note: static members can only operate static data or call static methods of classes. If you try to call non-static data or non-static methods, the compilation will be incorrect!

(2) Defining static data

If the class defines non-static data (instance data), each object of the type maintains an independent copy of the field, and each class instance allocates an independent memory.

For static data, the memory is allocated once and shared among all objects. Even if a new instance is created, the static data value is not reinitialized, because CLR allocates data to the memory only once. All objects share the same data.

Therefore, static members can only operate on static data. Non-static methods can use static data and non-static data, because static data is available for all instances of the type.

(3) Defining static Constructor

Static constructor is a special constructor,It is very suitable for initializing static data values unknown during compilation.(For example, you need to read values from external files or generate random numbers). Note the following:

  • A class can only define one static constructor;
  • Static constructors do not allow access to modifiers (for example, public static is incorrect) or accept any parameters;
  • No matter how many types of objects are created, the static constructor can only be executed once (that is, it can only be set once for static members );
  • Before the Runtime Library creates a class instance or accesses a static member for the first time, the Runtime Library calls the static Constructor (that is, the first time and only the class is used for the first time, the execution of the static constructor );
  • The execution of static constructor is prior to any instance level;
  • Obviously, this and base cannot be used to call constructors.
  • If the class has a static member variable, the system automatically provides a default static constructor. Otherwise, it is not provided by default.

(4) Defining static classes

After. net2.0, the concept of static classes is supported. It is used to extend the use of static keywords. If a class is defined as static, it cannot be created with the new Keyword. It can only contain members or fields identified with the static keyword, if we create a class that only contains static members or constant data, this is a good choice. (To prevent the class from being instantiated, we can only redefine the default constructor as private, or use the abstract keyword to indicate the abstract type ). With this type, the type is simpler and safer.

Tip: in fact, an application object (the class of the Main entry point) can be defined as a static class (not by default), so that it only contains static members and cannot be directly created.

5.3 pillars of OOP

Three object-oriented principles: inheritance, encapsulation, and polymorphism.

Encapsulation protects data integrity without understanding the implementation details.

Inheritance refers to the ability to create new class definitions based on existing class definitions. This is-a relationship is also called classic inheritance.

In OOP, there is another form of code reuse (not inheritance), that is, the inclusion/Reuse Model (has-a relationship, also called aggregation, for example, include another class in a class ).

Polymorphism represents the ability of a language to process objects in the same way. It allows the base class to define a member set for all the derived classes (Polymorphism Interface), A multi-state interface of the class type is composed of any virtual or abstract member.

Note: differentiate between multi-state interfaces and interface concepts. A virtual or abstract member of a multi-state interface allows a derived class to implement functions similar to interfaces.

5.4 access modifier

During encapsulation, you must consider which aspect of the type is visible to which part of our application. Accurately speaking, types and their members are always defined using a keyword to control how they are visible to other parts of the application.

Note:TheAccessIf no modifier statement is added before, the first is to directly access the method type in the definition method, second, class-level access (for static methods or static member variables) is performed outside the method type defined by the dot operator) alternatively, Class Object-level access (non-static methods or non-static member variables) includes classical inheritance to enable subclass to inherit members. With this concept, the following is easier to understand.AccessWe should also understand these three aspects.

Mainly include:

  • Public: modifier type (or structure) or type member, no restriction, can be accessed in internal or external assembly;

It is best to understand this,AccessThere are no restrictions.

  • Internal modifier type (or structure) or class members can only be accessed within the Assembly, meaning that "only the class that belongs to the same assembly can access this class or this member ";

This is actually a little more restrictive than public. If you access the internal class or internal method in the same program set, yesAccessUnrestricted (like public), but in another set of programs, it cannotAccessTo internal class or class internal method.

  • Private modifies the members or nested types of a class, which are accessed by the class (or structure) that defines them;

Therefore, the access here is only allowed within the declared type, and only meets the first of the above three access methods. That is to say, it cannot be accessed externally through the dot operator, not to mention the inherited access.

  • The member or nested type of the protected modifier class, which is accessed by defining its type or derived class (including direct access and access (if not static) through the derived class instance;

This is the most difficult to understand. Here we will summarize that, from the definition perspective, we can directly access from the type of the defined members and inherit from the subclass in line with the rules above, for the second condition, the constraint "defining the external type of this method" can only be a subclass (or, more accurately, a descendant class under this inheritance chain ), in addition, the Child class instance needs to access the protected member of the current class through the vertex operator. For example:

Public class Class_public {public void fun_public () {fun_protected (); // access through one of the methods} protected void fun_protected () {}} public class Class_child_public: class_public {public void fun_test () {Class_public PublicClass = new Class_public (); PublicClass. fun_public (); PublicClass. fun_internal (); // PublicClass. fun_protected (); // you cannot access it in this way. This is a common misunderstanding. fun_protected (); // you can access Class_child_public PublicChildClass = new Class_child_public () in the third way. PublicChildClass. fun_protected (); // This is our second method of constraint. // of course, it can also be accessed through the descendant class of Class_child_public.} public class Class_other {public void fun_test () {Class_child_public PublicChildClass = new Class_child_public (); // PublicChildClass. fun_protected (); // cannot be accessed, because it is not on the inheritance chain }}

It can be found that the protected member can only be accessed on its inheritance chain! A class (if both a base class and a derived class exist), the class member can access its own protected member or the protected member inherited from the base class, you can also access the protected member of an object of this type, or access the protected member of the object of the derived class.

  • Protected internal (or internal protected) modifies the Member or nested type of the class, which is available in the assembly or type that defines it or in the derived class. It means "access scope is limited to this AssemblyOrThe types derived from the classes it belongs ".

This statement is hard to understand. It is explained in detail: if a member of a certain class is declared as protected internal, the class located in the same assembly can access this member, however, a class located in another assembly cannot be accessed, unless the class located in another assembly is a subclass of the class where this member is located. This is actually the Union of internal and protected's accessibility.

Note:Type(For example, class) can only be modified by public or internal. All modifiers can be modified.Type Member, The last three types can also beModify nested type. This was not emphasized and paid attention to during reading.

The accessibility of members is shown in the following table:

Belong

Default accessible members

The declared accessibility allowed by this Member

Enum

Public

None

Class

Private

Public

Protected

Internal

Private

Protected internal

Interface

Public

None

Struct

Private

Public

Internal

Private

In addition, the types defined inside a class or structure are called nested types. For details, refer:

The http://msdn.microsoft.com/en-us/library/ms173120 (zh-cn, VS.80). aspx

Q: I can see from page 155th that public and internal modifiers can also be used for nested types. Why is this not provided in this article?

Default access modifier:

  • Type members are implicitly private)
  • The type is implicitly internal (Internal)
  • The nested type is implicit private)

The so-called implicit modifier is used by the compiler by default even if it is not manually added.

Q: should the default constructor be set to private automatically on page 128th? How to use private products?

A: Yes. If the class does not provide a default constructor, the default constructor provided by the system is indeed not private. If it is a self-written default constructor and is not modified, it is private and cannot be accessed. Therefore, the public modifier must be added.

5.5 attributes

The core concept of encapsulation is that internal data of objects should not be directly accessed from public interfaces. Encapsulation provides a method to protect the integrity of state data. Compared with defining public fields (data corruption is easy), more private data fields should be defined. Such fields can be operated indirectly by the caller. The operation methods include:

(1) define a pair of traditional access methods and modification methods

This requires that a private field be defined. If you need to operate on it, you should define two non-private methods to access and modify this private field, this indirectly completes operations on private fields. This technology requires two methods to operate a single data point.

(2) define a named attribute

Although the first method can meet the requirements, it still advocates the use of attributes to force data protection. For CLR, attributes are always mapped to "actual" access methods and modification methods.

Attributes consist of get and set scopes defined in the scope. The actual method of adding quotation marks is because at the underlying layer, the c # Attribute also uses methods to actually execute operations. In fact, the property is mapped to the hidden set_xxx/get_xxx method called by the CLR. Therefore, if you set an attribute named name, do not define methods such as set_name and get_name in the class (of course, the data field of this name will not work ~~ Otherwise, a conflict will be prompted during compilation!

It should be emphasized that these two methods are used for the same purpose. The attribute advantage is that the object user can use only one naming item to operate internal data.

Define an attribute as follows:

Private string empssn; public string socialnumber // similar to the definition variable, no () Oh {get {return empssn ;}// use return to return the property value set {empssn = value ;} // The value keyword is the attribute value! }

You can use modifiers for the accessibility of the entire attribute (private if not modified, inaccessible .)

If needed, you can also modify the accessibility of the set and get domains, such as protected get {empssn = value ;}. in this way, only the current class and the derived class can call the attributes for readability.

It should be noted that only when the attribute has both get accessors and set accessors can the accessors be accessed with the accessors modifier, that is, they cannot be individually modified only when set or get is followed. It can be understood that since there is only one, simply set this attribute to protected, and set a separate accesser separately, which makes little sense.

In addition, you cannot set modifiers for both the set and get accessors. The system will prompt "You cannot specify the accessable modifier for both accessors of the attribute ". Note that the access modifier of the set or get domain must not be more accessible than the modifier of this attribute.

Internal string socialnumber {public get {return empssn;} set {empssn = value ;}// if compilation fails, the following message is displayed: the Accessibility modifier of the get accessors must be more restrictive than the attribute or index appliance.

For attributes, you can also write only get or set. In this way, the read-only and write-only attributes are achieved!

Note: accessors must have stronger access modifiers than attribute or index appliance.

Static attributes:

The attribute can also be static. Of course, the operation of static attributes is the same as that of static methods. Static attributes can only operate on static data.

5.6 constant data and read-only fields

Constant data:

C # provides the const keyword to define a constant. After the initial value is defined, it cannot be changed. Note that you should use the class (or structure). Constant name to access the constant field, instead of the object. Constant name, because the constant field isImplicit static (implicitly static ),Therefore, access should be performed at the class level, and the static modifier cannot be added.

Note: constants must be definedPrimitive typeThe field can be of any type.

When defining const constant data, you must specify the initial value for the constant. Because the constant value must be known during compilation, it is wrong to assign values in the const function or elsewhere, because these (including constructors) are called at runtime.

Read-Only field:

The read-only field is modified with readonly. Similar to a constant, the read-only data field cannot be changed after the initial value is assigned. Unlike constants, the value assigned to a read-only field can be determined at runtime. Therefore, it is valid to assign values in the constructor scope, but not elsewhere (during runtime, read-Only fields cannot be assigned to non-constructors ). In addition, if no value is assigned to him, the system will give a default value!

Therefore, if you do not know the field value (for example, obtain the value from an external file) until running, and do not want it to be changed (otherwise, use a static constructor ), this type of read-only field is a good choice.

Unlike constant data, read-only fields are not implicitly static. after instantiation, they are accessed using the object. Read-Only field. Therefore, to access a static read-only field at the class level, use static to modify this read-only field, such as static readonly. Of course, if this static read-only field can only be assigned at runtime, the value should be assigned in the static constructor.

It's a bit confusing. Since all the data is constant, it's better to make the read-only field an implicit static one. Why do we still provide object-level access. It is mainly because read-only fields can be assigned values in the constructor. Therefore, different constant values may be required for different objects. In this case, different constant values must be set during the constructor.

Here is an introduction to the two easier to understand: http://blog.csdn.net/oec2003/archive/2009/06/22/4287927.aspx

Segment type of 5.7C #

In c #, classes and structures can be defined with a type modifier named partial, which allows defining the c # type across multiple *. cs files. In earlier versions, all the code of a type must be defined in one *. in cs, if there is a division type, it does not need such a long file. For example, after the compiler defines partial class emp in both places, the final result is still a unified type. This partial is purely a design-Time Structure and needs to be ensured at two points:

  • The type name (the above emp) must be consistent;
  • Defined in the same namespace.

5.8 generate C # source code documents using XML

C # provides a unique annotation tag to generate XML-based code documents. The symbol is three forward slashes (///), you can either directly comment in the code or in. in the. NET class Details window, input the XML code comments. The advantage is that the information can be viewed during smart sensing.

In some cases, after the code is documented using XML annotations, the corresponding xml file needs to be generated based on the xml file. This requires the/doc parameter of the csc compiler to be generated. Of course, you can also use. in the. NET platform, select generate-output XML file in project properties to specify the name and location of the file.

Next, you can convert the generated xml file to a user-friendly help format. VS. NET does not provide this function, but it can be generated using a third-party tool (NDOC or sandcastle. In this way, we can see help systems such as MSDN.

 

 

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.