"C #" chapter 3rd Learning Essentials (ii) custom classes and structures

Source: Internet
Author: User

Category: C #, VS2015

Date Created: 2016-06-19

Use of teaching materials: (Twelve-Five National planning Materials) "C # Program design and Application Course" (3rd edition) I. Essentials Overview

Others provide classes that are designed to simplify your workload, but the things you actually deal with vary greatly, and you have to define your own classes by writing code to do the real thing. Therefore, how to customize the class and its related concepts and points to grasp, is to write the program around the first level. Ii. Basic concepts of classes and members

1. Basic format

[ access modifier ] [Static] class name [: base class [, Interface sequence ]]

{

[ class member ]

}

Points:

(1) The base class can have at most one. If you do not define a base class, it is inherited from the system class by default.

(2) Class members include fields, properties, constructors, methods, events, operators, indexers, destructors, and so on.

(3) In most cases, you do not need to define destructors. You need to define a destructor only if you define the resources that you want to reclaim and not automatically clean them up by garbage collection.

Example:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapplication1{classPerson {Private Static intn =1;  Public stringName {Get;Set; } =string.        Empty;  Public intAge {Get;Set; } =0;  PublicPerson () {Console.WriteLine ($"{n++} times called"); }    }    classProgram {Static voidMain (string[] args) {person P1=NewPerson () {Name ="Zhang San", age = - }; Console.WriteLine ($"name: {P1. Name}, Age: {P1. AGE}"); Person P2=NewPerson () {Name ="John Doe", age = A }; Console.WriteLine ($"name: {P2. Name}, Age: {P2. AGE}");        Console.ReadLine (); }    }}

2. Access modifiers

(1) Basic access modifiers

Public: Both internal and external code of the class can be accessed.

Private: The inside of the class is accessible and the outside of the class is inaccessible. If you omit the access modifier for a class member, the default is private.

Internal: Code in the same assembly can be accessed, and other code outside the assembly cannot be accessed. If the access modifier for the class is omitted, the default is internal.

Protected: The inside of a class or a subclass inherited from that class can be accessed.

Protected internal: Subclasses inherited from this class, or classes inherited from another assembly, can be accessed.

(2) Special access modifiers

When the same class is described separately with several different files, you can also add the partial modifier after the base access modifier. For example, when multiple people write the same class at the same time, this can be used.

When the compiler compiles a source program, it is automatically merged into the same class.

3. Constructor function

Points:

(1) A constructor is a function that is called automatically when an object is created. It is common to do some initialization work in the constructor, or to do some specific actions that need to be performed only once.

(2) The constructor does not have a return type, and its name is the same as the name of the class to which it belongs.

(3) constructors can be overloaded.

(4) When calling the method provided by the base class in the constructor of the extension class, it is implemented with the "base. Method Name".

4. Static class and Static method

Points:

(1) The addition of static to the method name indicates that this is a static method.

(2) You can add static in front of class to indicate that the defined class is a static class. In this case, all the members in the class must be static (all must have the static modifier).

(3) in the C # language, call the static method with "class name. Method name" to invoke the instance method through "instance name. Method Name".

(4) Static methods can be overloaded but cannot be overridden.

Attention:

(1) A member declared as static has only one copy in memory.

(2) The first call is loaded into memory and all members are removed from memory when they are no longer called, and the work is done automatically by the garbage collector.

5. Properties

Points:

(1) A property is an extension of a field that provides the means to read and write to a field.

(2) The difference between a property and a field is that a property does not represent a storage location, but rather a statement that needs to be executed when a read-write value is specified by a get accessor and a set accessor. Depending on the usage, you can provide either a get accessor or a set accessor only, or both.

(3) Basic Usage Example:

public string Name {get; set;} = String. Empty;

public int Age {get; set;} = 0;

public int Grade {get; private set;}

6. Methods

Points:

(1) When defining a method, the keywords you can use before the parameter name are:

Ref, out, params

(2) If you define a method without adding a keyword in front of the parameter name, be aware of the difference in invocation between value types and reference types by default.

(3) Method overloading

Multiple methods that have the same method name but are not exactly the same as the parameter type or number of arguments can appear in the same class at the same time. In the project development process, many methods need to be implemented using method overloads.

7. Events

Events are implemented by delegates. Because of the extensive use of delegates and events to accomplish various functions in a project, it is described later in a separate chapter.

8. Encapsulation, inheritance, and polymorphism of classes

is a high-level usage, and has a great relationship with programming experience, it is a beginner's difficulty but also is the best embodiment of the core technology advantages and differences in the project place.

(1) Package

Abstract class: Declared with the abstract keyword. Abstraction is the extraction of common things into a single class, which requires that the extension class must implement some method that only declarations are not implemented in the abstract class, and some common methods can be implemented directly in the abstract class.

Sealed class: Declared with sealed keyword. Using the keyword in the definition of a class indicates that the class cannot be inherited, and using that keyword in the definition of a method indicates that the method cannot be overridden.

(2) Inheritance

The purpose of inheritance is to avoid repeatedly writing the same code. If you describe it in a less rigorous way, you can think of it as a hierarchical management of what you want to deal with.

Be aware of the handling of constructors in inheritance.

(3) polymorphic

Note the use of the following keywords:

Virtual, override: A method definition of a base class with virtual means that the method can be overridden by an extended class, in which an extension class overrides the method that has the same name in the base class.

NEW: The method definition of the base class is not declared with virtual (that is, it is not allowed to be overridden), but you still need to rewrite it, and you can use this keyword at this time. III. Custom Structure

Points:

(1) When customizing the structure, use the struct keyword. In terms of definition, it differs from the class in that only one word is different (structs are declared with the struct keyword, and classes are declared with the class keyword), the others are the same.

(2) The structure cannot be inherited.

(3) The difference between a struct and a class is performance: The variable value of the structure is stored in the stack (fast), and the variable value of the class is saved in the heap (slower).

(4) Any custom structure can be implemented by a custom class. If the structure is not clear or good use of the class, it is not considered performance, all use the class to achieve the line. As the development experience increases, you will naturally understand which situations should be implemented in a structure.

"C #" chapter 3rd Learning Essentials (ii) custom classes and structures

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.