c# - 为什么在嵌套类上调用方法时不调用父类的静态构造函数?

标签 c# static-constructor

给定以下代码,为什么在“Main”的第一行之后不调用“Outer”的静态构造函数?

namespace StaticTester
{
    class Program
    {
        static void Main( string[] args )
        {
            Outer.Inner.Go();
            Console.WriteLine();

            Outer.Go();

            Console.ReadLine();
        }
    }

    public static partial class Outer
    {
        static Outer()
        {
            Console.Write( "In Outer's static constructor\n" );
        }

        public static void Go()
        {
            Console.Write( "Outer Go\n" );
        }

        public static class Inner
        {
            static Inner()
            {
                Console.Write( "In Inner's static constructor\n" );
            }

            public static void Go()
            {
                Console.Write( "Inner Go\n" );
            }
        }
    }
}

最佳答案

规范的第 10.12 节回答了您的问题,其中指出:

The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

• An instance of the class type is created.

• Any of the static members of the class type are referenced.

因为你没有做这两件事,所以 ctor 没有被执行。

关于c# - 为什么在嵌套类上调用方法时不调用父类的静态构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2629669/

相关文章:

c++ - C++中的静态构造函数?我需要初始化私有(private)静态对象

c# - 对于此 c# 控制台应用程序 + Access 2007 方案,我应该使用哪种数据访问方法?我要林克!

c# - 在 Entity Framework 6 中使用一个 linq 查询选择多个对象

c# - 将序列号添加为 GridView 中的第一列

c# - 静态构造函数如何工作?

c# - RunClassConstructor 是否保证只运行一次类型的静态构造函数?

c# - 在 .Net Core 中使用 CSharpCodeProvider

C# Http.Response 流返回内容类型为 application/json 的空字符串

c# - 如何确保在不调用任何成员的情况下调用静态构造函数

entity-framework - 静态构造函数中的 Database.SetInitializer()?