想知道C# private的构造函数的具体用处,希望有相关场景或例子。
说白了就是不太清楚“不被别人调用”可以用在什么地方~
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;
}
}
}