C#私有的构造函数的作用:当类的构造函数是私有的时候,也已防止C1 c1=new C1();实例化类。常见的应用是工具类和单例模式。
using System;
using System.Collections.Generic;
namespace NetGraphical
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine(C1.meb1);
Console.WriteLine("--------------1");
C1 c1 = new C1();
Console.WriteLine("--------------2");
Singleton.getInstance();
}
}
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()
{
}
public static Singleton getInstance()
{
if (s == null)
{
s = new Singleton();
}
return s;
}
}
}