静态构造函数:静态构造函数没有修饰符没有参数,一个类只能有一个静态构造函数,静态函数只会被执行一次,静态函数是在类被实例化或者静态成员被调用时才会执行
class StaticConstructor
{
static void Main()
{
b b1 = new b();
a a1 = new a();
Console.WriteLine(a.strText);
Console.WriteLine(b.strText);
Console.Read();
}
}
public class a
{
public static string strText;
public string Text;
static a() {
strText = "aaa";
}
public a()
{
Text = "aaaaaaaaaa";
}
}
public class b :a
{
static b()
{
strText = "bbb";
}
public b()
{
Text = "bbbbbbbbbbbb"; }
}
输出结果为bbb的原因是实例化b,由于继承了a,先调用a的静态构造函数,然后strtext就被赋值为aaa,然后在调用b的静态构造函数,strtext被赋值为bbb,由于静态构造函数只被调用一次所以输出为bbb
详见:https://www.cnblogs.com/jiagoushi/p/3775046.html
私有构造函数:使用private声明,类不能再被实例化
class PrivateConstructor
{
static void Main() {
Console.WriteLine(c1.meb1);
Console.WriteLine("-------------1");
c1 c2 = new c1();
Console.WriteLine("------------2");
Singleton.getInstacne();
Console.Read();
}
}
class c1 {
public static int meb1 = 10;
static c1()
{
Console.WriteLine("static constructed function:"+meb1);
meb1 = 20;
}
public c1() {
Console.WriteLine("constructed function");
}
}
class Singleton {
private static Singleton s = null;
private Singleton() {
Console.WriteLine("i am singleton");
}
public static Singleton getInstacne()
{
if (s == null) {
s = new Singleton();
}
return s;
}
}
析构函数和dispose方法处理非托管资源:
一般用dispose方法来释放非托管资源,用析构函数的话第一步会调用析构函数第二步会删除对象,因为析构函数有大量的释放非托管资源的代码,降低垃圾回收器的工作效率,影响性能。
托管资源:一般是指.net可以自动回收的资源,主要值托管堆上的内存分配,有垃圾回收器进行回收
非托管资源:一般指的是不知道如何回收的资源,列如:文件,窗口,数据库连接,网络连接,图标。
class DisposeAndDestructor:IDisposable
{
private IntPtr handle;
private Component comp;
private bool isDisposed=false;
public DisposeAndDestructor (){ }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~DisposeAndDestructor()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing) {
if (!this.isDisposed) {
if (disposing) {
comp.Dispose();
}
CloseHandle(handle);
handle = IntPtr.Zero;
}
this.isDisposed = true;
}
private void CloseHandle(IntPtr handle)
{
throw new NotImplementedException();
}
}
详见:https://blog.csdn.net/zlwzlwzlw/article/details/7918633