C # Key knowledge detailed (2)

zhaozj2021-02-08  260

Guide: C # memory management provides the same automatic memory management function as Java, so that programmers get rid of heavy memory management, memory management improves code quality and improves development efficiency.

Author: wkrain www.ASPCool.com

Chapter 2 Memory Management

C # memory management provides the same automatic memory management function as Java, allowing programmers to get rid of heavy memory management, and memory management improves the quality of code and improves development efficiency.

C # limits the use of the pointer, eliminating the troubles of programmers, but does not mean that C # programmers do not use the benefits of pointers like the Java programmers. Microsoft takes this question when designing C # language, and on the one hand, while discarding the pointer, on the other hand, it uses a compromised approach to introduce a pointer through a logo.

First let's understand the automatic memory management

Public Class Stack

{

Private node first = NULL;

Public bool empty {

Get {

Return (first == null);

}

}

Public Object Pop () {

IF (first == null)

Throw new Exception ("CAN't Pop from an Empty Stack.");

Else {

Object temp = first.value;

FigSt = first.next;

Return Temp;

}

}

Public void push (Object O) {

First = new node (o, first);

}

Class node

{

Public node next;

Public Object Value;

Public Node (Object Value): this (value, null) {}

Public Node (Object Value, Node Next) {

NEXT = NEXT;

Value = value;

}

}

}

The program creates a Stack class to implement a chain, use a PUSH method to create a Node node instance and a collector when the Node node is no longer required. A node instance cannot be accessed by any code, it is collected. For example, when a point element is removed, the associated Node is collected.

The Example

Class test

{

Static void main () {

Stack s = new stack ();

For (int i = 0; i <10; i )

S.push (i);

s = NULL;

}

}

With regard to the reference to the pointer, use the UNSAFE flag in C # to represent the reference to the team pointer. The following program demonstrates the usage of pointers, but due to the use of pointers, memory management has to be completed.

Using system;

Class test

{

UNSAFE Static Void Locations (Byte [] ar) {

Fixed (byte * p = ar) {

BYTE * P_ELEM = P;

For (int i = 0; i

BYTE value = * p_lex;

String addr = int.format ((int) p_lem, "x");

Console.writeline ("Arr [{0}] AT 0x {1} IS {2}", i, addr, value);

P_lem ;

}

}

}

Static void main () {

Byte [] arr = new byte [] {1, 2, 3, 4, 5}; Writelocations (ar);

}

}

转载请注明原文地址:https://www.9cbs.com/read-2326.html

New Post(0)