为什么不是父类中的嵌套类调用方法时调用的静态构造函数? [英] Why isn't the static constructor of the parent class called when invoking a method on a nested class?

查看:263
本文介绍了为什么不是父类中的嵌套类调用方法时调用的静态构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码,为什么不是外,主的第一行后调用的静态构造函数?



 命名空间StaticTester 
{
类节目
{
静态无效的主要(字串[] args)
{
Outer.Inner.Go() ;
Console.WriteLine();

Outer.Go();

到Console.ReadLine();
}
}

公共静态部分类外
{
静态外()
{
Console.Write(外的静态constructor\\\
);
}

公共静态无效围棋()
{
Console.Write(外Go\\\
);
}

公共静态类内
{
静态内部()
{
Console.Write(内蒙古的静态constructor\ N);
}

公共静态无效围棋()
{
Console.Write(内Go\\\
);
}
}
}
}


解决方案

在嵌套类的情况下,如果嵌套类从未提及它的静态成员的外部范围,编译器(和CLR)不需要调用,静态构造函数外部类。



如果要强制静态构造函数运行,只需添加代码,以执行一个领域或财产的读内部类型外类型。



您可以阅读更多关于的乔恩斯基特的博客 - 这是相当不错的。你也可以检查出他的书 - C#在深度,它涵盖了这些主题,以及...深度

Given the following code, why isn't the static constructor of "Outer" called after the first line of "Main"?

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" );
            }
        }
    }
}

解决方案

In the case of nested classes, if the nested class never refers to the static members of it's outer scope, the compiler (and CLR) are not required to call the static constructor of that outer class.

If you want to force the static constructor to run, just add code to the inner type that performs a read of a field or property of the outer type.

You can read more about the lazy initialization semantics of C# on Jon Skeet's blog - it's quite good. You could also check out his book - C# In Depth, it covers these topics as well ... in depth.

这篇关于为什么不是父类中的嵌套类调用方法时调用的静态构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆