C#重點知識詳解(二)
2024-07-21 02:20:00
供稿:網友
,歡迎訪問網頁設計愛好者web開發。第二章 內存管理
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);
}
}