Step by step, basic. NET [object-oriented constructor and destructor],. net Constructor
Constructor and destructor
Constructor:
Syntax:
// Constructor without Parameters
[Access modifier] function name (); the function name must be the same as the class name.
// Constructor with Parameters
[Access modifier] function name (parameter list). The function name must be the same as the class name.
Purpose: Help us initialize the object (assign values to each attribute of the object in turn)
Constructor is a special method:
1) The constructor does not return values and cannot write void.
2) The constructor name must be the same as the class name.
3) whether the constructor has parameters or has parameters.
The constructor is executed when an object is created. The constructor can be overloaded.
***
Class will have a default non-parameter constructor. After you write a new constructor, whether there are parameters or no parameters, the default no-parameter constructor is killed.
Code display:
// Define a class:
public class Student{ private string _name; public string Name { get { return _name; } set { _name = value; } } private int _age; public int Age { get { return _age; } set { _age = value; } } }View Code
// Define a constructor without Parameters
Public Student () {Console. WriteLine ("I am the constructor !!! ");}View Code
// Define constructors with Parameters
public Student(string name, int age ) { this.Name = name; this.Age = age; }View Code
Destructor:
Syntax :~ ("~") Function name. The function name must be the same as the class name.
Rule: A class can have only one destructor;
The Destructor cannot be overloaded;
The Destructor cannot be displayed or manually transferred, and can only be automatically called by the garbage collection bin (GC.
Note: destructor do not accept any parameters or any access modifiers. The main body of the Destructor includes some code, which is usually used to close the database, file, or network connection opened by the instance.
Code display:
public class Student{ private string _name; public string Name { get { return _name; } set { _name = value; } } private int _age; public int Age { get { return _age; } set { _age = value; } } }View Code
// Destructor
// The Destructor is executed only when the program ends. // It helps us release resources. // GC Garbage Collection ~ Student () {Console. WriteLine ("I am an destructor ");}View Code
Summary:
Constructor: used to initialize objects.
Destructor: release resources.
This article is here, and finally a small advertisement: QQ group: . NET Step by stepGroup Number:590170361 (Add group remarks: what you see in the blog Park)