比如这样 public class config { int x; }public class myTest { public static config cfg; public static myTest() { cfg = new config(); } }这样是第一次使用cfg的时候,就会调用静态构造函数,在你程序退出时候,才会释放cfg吧。计数器?这个,应该和COM不同的吧。如果这样,岂不是静态构造函数会调用多次了?至于什么时候卸载,应该是最后。后面是否会使用这个静态变量,clr貌似无法知道吧。
所以可以用以下方法
class yourclass
{
static int nuse;
static nomanager m_p;
public static nomanager P{
get{
if( p == null )
{
nuse = 0;
p = new ...
return p;
}
}
}
~yourclass()
{
nuse--;
if( nuse == 0 )
delete p;
}}
get{
nuse++;
if( p == null )
{
p = new ...
return p;
}
}
CLR或者编译器是不会知道什么时候该类不会再被引用和创建实例的。
public class config
{
int x;
}public class myTest
{
public static config cfg;
public static myTest()
{
cfg = new config();
}
}这样是第一次使用cfg的时候,就会调用静态构造函数,在你程序退出时候,才会释放cfg吧。计数器?这个,应该和COM不同的吧。如果这样,岂不是静态构造函数会调用多次了?至于什么时候卸载,应该是最后。后面是否会使用这个静态变量,clr貌似无法知道吧。
实际上,在程序结束的时候执行就行了,因为如果程序结束了,CLR就可以确信这个类不会再被引用了(如果c#有静态析构的话,我想也会在程序结束时执行吧)。这个释放过程当然可以自己写到程序的结尾,只是有点破坏OOP而已啦。。
=====
如果是非托管资源呢??
class Test
{
static x m_x = new x();
static void Main()
{
}
}
class x : IDisposable
{
public void Dispose()
{
System.IO.File.AppendAllText("f:\\a.txt", "hello world!");
GC.SuppressFinalize(this);
}
~x()
{
//System.IO.File.AppendAllText("f:\\a.txt", "hello world!");
}
}
但一定记住任何托管资源都不应在析构函数中处理,即使是间接的非托管资源,例如SqlConnection。非托管资源是指你直接用P/Invoke调用或是不安全代码动态分配的内存。
{
static Program()
{
Console.WriteLine("Program Start");
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
} static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("Program Stop");
} static void Main(string[] args)
{
Console.WriteLine("Program Run");
}
}