给定以下代码,为什么在“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/