中国开发网: 论坛: 程序员情感CBD: 贴子 513231
mhappy
继续问,请看示例代码。。。
// Demonstrate a destructor.

using System;

class Destruct {
public int x;

public Destruct(int i) {
x = i;
}

// called when object is recycled
~Destruct() {
Console.WriteLine("Destructing " + x);
}

// generates an object that is immediately destroyed
public void generator(int i) {
Destruct o = new Destruct(i);
}

}

class DestructDemo {
public static void Main() {
int count;

Destruct ob = new Destruct(0);

/* Now, generate a large number of objects. At
some point, garbage collection will occur.
Note: you might need to increase the number
of objects generated in order to force
garbage collection. */
for(count=1; count < 100000; count++)
ob.generator(count);

Console.WriteLine("Done");
}
}
Here is how the program works. The constructor sets the instance variable x to a known value. In this example, x is used as an object ID. The destructor displays the value of x when an object is recycled. Of special interest is generator( ). This method creates and then promptly discards a Destruct object (because o goes out of scope when generator( ) returns). The DestructDemo class creates an initial Destruct object called ob. Then using ob, it creates 100,000 objects by calling generator( ) on ob. This has the net effect of creating and discarding 100,000 objects. At various points in the middle of this process, garbage collection will take place.


不是说c#不会在超出SCOPE后析构么?

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录