C# 中的静态构造函数是否存在默认构造函数?

Do default constructor exists with static constructor in C#?

我对实例中的静态构造函数感到困惑 class。

由于默认情况下静态构造函数是私有的,我们不能对它们使用访问修饰符,那么实例中是否存在默认构造函数和静态构造函数class?

如果是,那为什么?因为我们已经定义了一个构造函数(private static 和 parameter less),并且根据 C# 概念,如果我们提供一个构造函数,那么默认构造函数将不存在。 (我这里可能是错的)

如果否,那么为什么我们能够使用静态构造函数创建实例对象class。

下面的例子被编译并执行成功:

public class OOPS
{
    static int i = 0;
     static OOPS(){             
        Console.WriteLine("Static Constructor ");
    }

    //OOPS() {
    //    Console.WriteLine("Instance Constructor");
    //}

    public static void ShowStaticMethod() {
        Console.WriteLine("Static Method  ");
    }

    public void ShowInstanceMethod()
    {
        Console.WriteLine("instance Method");
    }
}

class Client
{
    public void ClientMethod() {
        OOPS o = new OOPS();
        o.ShowInstanceMethod();
        OOPS.ShowStaticMethod();
        Console.WriteLine("Client completed");                       
        Console.ReadLine();
    }        
}

if we provide a constructor then the default constructor won't exists. (I might be wrong here)

好吧,有一件事你错了,上面的说法是关于 实例构造函数 的,而不是静态构造函数。

看看 C# language specification.

10.11.4 Default constructors

If a class contains no instance constructor declarations, a default instance constructor is automatically provided.

因此,当您提供静态构造函数时,它与默认实例构造函数没有任何关系,而这正是您稍后在代码中使用的实例构造函数。

静态构造函数不影响实例构造函数。如果您不想实例化 class,请将 class 标记为 static

public static class OOPS
{
   static OOPS()
   {
   }
}