c# - 如何在静态类中调用静态构造函数

Gob*_*ind 0 c# c#-4.0

我是 C# 的新手。请指导我找出这个问题的解决方案。我有一个静态类 A。在这个里面我有一个静态构造函数。代码如下:

using System; 
using System.Collections.Generic;
using System.Linq; 
using System.Text;
namespace ConsoleApplication6 
{
    class Program 
    { 
        static void Main(string[] args) 
        { 
        } 
    } 
    static class A 
    { 
        static A() 
        { 
            Console.WriteLine("static constructor is called."); 
        } 
    } 
}
Run Code Online (Sandbox Code Playgroud)

如何在 c# 中访问这个静态构造函数?

Sam*_*sov 7

你不能。正如 MSDN 文章关于静态类所写的那样:

静态类与非静态类基本相同,但有一个区别:静态类不能被实例化。换句话说,您不能使用 new 关键字来创建类类型的变量。由于没有实例变量,您可以使用类名本身访问静态类的成员。

我也建议你阅读这篇文章

静态构造函数(C# 编程指南)

正如所写的那样,您不能调用静态构造函数

静态构造函数用于初始化任何静态数据,或执行只需要执行一次的特定操作。在创建第一个实例或引用任何静态成员之前自动调用它 。

静态构造函数具有以下属性:

  • 静态构造函数不接受访问修饰符或参数。

  • 在创建第一个实例或引用任何静态成员之前,会自动调用静态构造函数来初始化类。

  • 不能直接调用静态构造函数。

  • 用户无法控制程序中何时执行静态构造函数

下面是静态构造函数如何工作的示例。

using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication6 
{
    public class Program 
    { 
        public static void Main(string[] args) 
        { 
            A myClass1WithStaticConstructor = new A();
            A myClass2WithStaticConstructor = new A();
        } 
    } 
    public class A 
    { 
        public A()
        {
            Console.WriteLine("default constructor is called."); 
        }
        static A() 
        { 
            Console.WriteLine("static constructor is called."); 
        } 
    } 
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

静态构造函数被调用。
调用默认构造函数。
调用默认构造函数。

所以从输出我们看到静态构造函数只被第一次调用。

另外,如果您想将它与静态类一起使用,这里是它的示例:

using System; 
using System.Collections.Generic;
using System.Linq; 
using System.Text;
namespace ConsoleApplication6 
{
    public class Program 
    { 
        public static void Main(string[] args) 
        { 
            Console.WriteLine(A.abc);
        } 
    } 
    public static class A 
    { 
        public static int abc;

        static A() 
        { 
            abc=10;
            Console.WriteLine("static constructor is called."); 
        } 
    } 
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

静态构造函数被调用。
10

所以我们看到在这种情况下也会自动调用静态构造函数。