- Construction method
- The constructor method is a special method that is responsible for initializing the object
- The constructor method name must match the class name
- The construction method has no return value, but can have parameters that can overload
- The construction method can not be written, and the system automatically adds an argument-free default construct to the class
- If you set the construction method to private, you can no longer use this construct to create an instance
- Destruction
- Destructors are called when an object is destroyed to free memory
- A class can have only one destructor method
- Destructors do not return values and parameters and cannot be overloaded
- The destructor method is automatically called by the system and cannot be called manually.
- destructor does not have modifiers
-
1 usingSystem;2 3 namespaceFunctionDemo24 {5 Public class Person6 {7 Public stringname;8 Public intAge ;9 //Construction Method-responsible for initializing the objectTen //1. The method name of the construction method must be the same as the class name One //2. The construction method has no return value and does not require write void A - //3. Constructor method to add parameters - PublicPerson (stringNameintAge ) the { - //Initializing member variables - This. Name =name; - This. Age =Age ; +Console.WriteLine ("Construction"); - } + A //4. Construction method allows overloading at PublicPerson () - { -Name ="Li"; -Age = -; - - } in //5. If you do not add a constructor method to a class, the system provides a default construct - //6. If we set a construction method to a private class, we are not allowed to create the object through this construct to //Private person () + //{ - the //} * //destructor-Called when an object is destroyed to free memory $ //1. Each class can have only one destructor methodPanax Notoginseng //2. Destructors cannot have return values - //3. Destructors cannot have access modifiers the //4. Destructors cannot have parameters and cannot be overloaded + //5. Destructors are automatically called by the system and cannot be called manually A~Person () the { +Console.WriteLine ("Destruction"); - } $ } $ class Program - { - Static voidMain (string[] args) the { - //When you create an object using the New keyword, you have called the construction methodWuyiPerson p =NewPerson ("Li", in); the Console.WriteLine (p.name); - Console.WriteLine (p.age); Wu -Console.WriteLine ("The main function ends and the program is ready to exit! "); About $ //Person p2 = new Person (); - //Console.WriteLine (p2.name); - //Console.WriteLine (p2.age); - A } + } the}
"Learning Notes" C # Construction and destruction