你在这里混合了一些不同的东西
静态类public static class MyClass
只能包含静态元素并且永远不会被初始化
构造函数(无论是公共的还是私有的)总是在类的实例中创建,公共或私有仅表示构造函数的可见性。
这通常在实现单例设计时使用
private MyClass()
{
}
private static MyClass _Singleton;
public static MyClass Singleton
{
get
{
if(_Singleton==null) _Singleton = new MyClass();
return _Singleton
}
}
}
另一个是类初始化器,这有点令人困惑,因为它的语法与构造函数非常相似,只是添加了静态关键字和缺少参数
static MyClass()
{
//configure static variables on first us only
b = //read value from file or other resource not avalable at compile time
a = b.Lenth; //can't be be done in class body as b would not have been initialised yet
}
private static int a;
private static string b;
因此,如果您的类无法实例化,那么您只能将其声明为静态,否则不会这样做,
如果您调用私有构造函数,则每次调用都会创建一个实例
类初始化器永远不能在第一次使用类时自动调用,并且不会创建实例
编辑:这是您的测试程序的修订版
public static class StaticClassExample
{
public static void ClassFunction()
{
Console.WriteList("This is a class function")
}
}
public static class InitialisedStaticClassExample
{
static InitialisedStaticClassExample()
{
Console.WriteList("This class has been initialised")
}
public static void ClassFunction()
{
Console.WriteList("This is a class function")
}
}
public class PrivateConstuctorClassExample
{
static PrivateConstuctorClassExample()
{
Console.WriteList("This class has been initialised")
}
private PrivateConstuctorClassExample()
{
Console.WriteList("This class has been Instantiated")
}
public static void ClassFunction()
{
Console.WriteList("This is a class function");
var instance = new PrivateConstuctorClassExample();
instance.InstanceFunction();
}
public void InstanceFunction()
{
Console.WriteList("This is a instance function")
}
}