static class 中的方法是如何调用的

How is the method called in static class

我的代码如下

   class MyStaticClass
   {

     static MyStaticClass{};

    public static readonly MyStaticClass Instance = CreateMe();
    public static int GetSomeValue = GetValue();

    private static int GetValue()
    {
        return 0;
    }

    private static MyStaticClass CreateMe()
    {
        Console.WriteLine("This method was called");
        return new MyStaticClass();
    }

}

public class 程序 {

    public static void Main()
    {

         int val=MyStaticClass.GetSomeValue;

    }
 }

O/p:

This method was called

当我调用 val 时,为什么调试器会访问 CreateMe 方法?是不是我访问它的任何静态方法都会访问 class 中的所有静态方法?

方法CreateMe()被调用是因为你在下面的语句中创建对象Instance时调用了。

 public static readonly MyStaticClass Instance = CreateMe();

这是您 class 中的静态对象,是在您访问 MyStaticClass.GetSomeValue 时创建的 class。

Dubugging the code will give you clear view of the order of the statements get executed. You can go through this detailed article on MSDN regarding debugging Debugger Roadmap

您有一个静态字段的静态初始值设定项。作为程序启动的一部分,所有静态字段都会被评估。

编辑: 此处的小说明:

特定 class 中的静态字段按声明顺序求值,但 class 没有特定顺序首先初始化静态字段。 现在,如果你有一个静态 属性,那就不一样了。

MSDN link

两个字段都已使用静态方法初始化。因此,在这种情况下,将评估所有静态方法。