C study notes sorting _ in depth analysis of constructors and destructors

  • 2021-11-10 10:29:40
  • OfStack

Constructor, destructor

Constructor:

1. If no constructor is provided, the system will automatically provide a default constructor, initializing all members to default values (reference type is null reference null, value type is 0, bool type is false);

2. If a constructor with parameters is provided, the system does not provide a default constructor;

3. The constructor can be overloaded: multiple different versions of the constructor can be provided, which can be distinguished according to the number and type of parameters;

4. Private constructor: The object cannot be instantiated by this constructor, but can be instantiated by calling a static function; When used only as a container for certain static members or attributes, private constructors can be defined to prevent instantiation;

1-like constructors are instance constructors, which are executed as long as an instance is created;

Static constructor:

1. You can define only one, run at most once, and only call it by the. NET runtime before the first call to any member of the class,

2. It can't take any parameters and access modifiers, and can only access static members of the class, but can't access instance members of the class;

3. If the class has 1 static field and the properties need to be initialized from an external source before the first use of the class, use the static constructor;

4. The static constructor and the instance constructor without parameters can be defined at the same time, and when to execute which constructor will not conflict;

In the constructor, you can call other constructors of your own: this (), or the constructor of your parent class: base (), and you can call other constructors similar to inherited syntax;

Read-only field readonly: Similar to constant const, its value cannot be modified, but read-only field is declared with readonly, which can be uninitialized, initialized in constructor, and then its value cannot be changed;

Instantiation of anonymous types: var a = new {f1= "1ad", f2= "34", f3=5, f4=6};

Constructor: Used to destruct an instance of a class

You cannot define a destructor in a structure. You can only use destructors on classes.

A class can only have one destructor.

The destructor cannot be inherited or overloaded.

The destructor cannot be called. They are called automatically. Controlled by the garbage collector, if the garbage collector considers an object to be destructible, it calls the destructor (if any) and reclaims the memory used to store the object. The destructor is also called when the program exits

The destructor has neither modifiers nor parameters

You can force garbage collection by calling Collect, but in most cases you should avoid doing so because it can cause performance problems

C # does not require much memory management. This is because the. NET Framework garbage collector implicitly manages the memory allocation and release of objects. However, when your application encapsulates unmanaged resources such as windows, files, and network connections, you should use destructors to release those resources. When the object complies with destruction, the garbage collector runs the Finalize method of the object.

If your application is using expensive external resources, we also recommend that you provide a way to explicitly release resources before the garbage collector releases objects. This is accomplished by implementing the Dispose method from the IDisposable interface, which performs the necessary cleanup for the object. This can greatly improve the performance of the application. Even with this explicit control over resources, the destructor is a protective measure that can be used to clean up resources if a call to an Dispose method fails


class Car

{

  -Car() 

  {

    //  …   … 

  }

}

The destructor implicitly recursively calls the Finalize () method for all instances in the inheritance chain


public class Bus
 {
   protected static readonly DateTime globalStartTime;
 
   protected int RouteNumber { get; set; }
 
   static Bus() // Static constructor 
   {
 globalStartTime = DateTime.Now;
 Console.WriteLine("Static ctor sets global start time to {0}", globalStartTime.ToLongTimeString());
   }
 
   public Bus(int routeNum)
   {
 RouteNumber = routeNum;
 Console.WriteLine("{0} is created.", RouteNumber);
   }
 
   public void Drive()
   {
 TimeSpan elapsedTime = DateTime.Now - globalStartTime;
 
 Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
             this.RouteNumber,
             elapsedTime.TotalMilliseconds,
             globalStartTime.ToShortTimeString());
   }
 }
 
 class TestBus
 {
   static void Main()
   {
 
 Bus bus = new Bus(71);
 bus.Drive();
 System.Threading.Thread.Sleep(25);
 
 Bus bus2 = new Bus(72);
 bus2.Drive();
 
 System.Console.WriteLine("Press any key to exit.");
 System.Console.ReadKey();
   }
 }
 /* Output:
   Static ctor sets global start time to 10:04:08 AM
   71 is created.
   71 is starting its route 21.00 minutes after global start time 10:04 AM.
   72 is created.
   72 is starting its route 46.00 minutes after global start time 10:04 AM.   
*/

Related articles: