第二章 內存管理
c#內存管理提供了與java一樣的自動內存管理功能,讓程序員從繁重的內存管理中擺脫出來,內存管理提高了代碼的質量和提高了開發效率。
c#限制了著指針的使用,免除了程序員對內存泄漏的煩惱,但是不是意味著向java程序員一樣c#程序員在也不能使用指針代來的好處。微軟在設計C#語言時考慮到這個問題,在一方面拋棄指針的同時,另一方面采用折衷的辦法,通過一個標志來時程序引入指針。
首先我們來了解自動內存管理
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; first = 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; } } }
程序創建了一個stack類來實現一個鏈,使用一個push方法創建Node節點實例和一個當不再需要Node節點時的收集器。一個節點實例不能被任何代碼訪問時,就被收集。例如當一個點元素被移出棧,相關的Node就被收集。
The example
class Test { static void Main() { Stack s = new Stack();
for (int i = 0; i < 10; i++) s.Push(i);
s = null; } }
關于指針的引用,c#中使用unsafe標志來代表隊指針的引用。以下程序演示了指針的用法,不過由于使用指針,內存管理就不得不手工完成。
using System;
class Test { unsafe static void Locations(byte[] ar) { fixed (byte *p = ar) { byte *p_elem = p; for (int i = 0; i < ar.Length; i++) { byte value = *p_elem; string addr = int.Format((int) p_elem, "X"); Console.WriteLine("arr[{0}] at 0x{1} is {2}", i, addr, value); p_elem++; } } }
static void Main() { byte[] arr = new byte[] {1, 2, 3, 4, 5}; WriteLocations(ar); } <>
|