为什么静态构造函数类的方法首先调用之前不叫 [英] Why static constructor not called before first call to class method

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

问题描述

据乔恩斯基特的条每页下在的,并讨论= http://stackoverflow.com/questions/1437352/when-is-a-static-constructor-called-in-c">When是一个静态构造函数调用C#?静态构造函数必须首先调用之前调用到类的方法。

According to Jon Skeet's artice C# and beforefieldinit and discussion in When is a static constructor called in C#? static constructor must be called before first call to a method of the class.

由于某些原因如下code不会出现此行为:

For some reason following code does not exhibit this behavior:

namespace AbstractAndStatic
{
    class Program
    {
        static void Main(string[] args)
        {
            StaticClass.Equals(1,2);
            StaticClass.foo();
        }
    }
    static class StaticClass : Object
    {
        public static void foo()
        {
            Console.WriteLine("Static");
        }
         static StaticClass()
        {
            Console.WriteLine("static constructor");
        }
    }
    class TestClass
    {
        public void deb()
        {
            Console.WriteLine("Test Class Debug");
        }
    }
}     

我调试使用Visual Studio调试上述code。当语句 StaticClass.Equals(1,2); 被Main方法执行的静态构造函数是没有得到所谓的,但是当 StaticClass.foo( ); 执行它调用静态构造函数,然后调用foo的方法。

I am debugging the above code using the Visual Studio Debugger. When the statement StaticClass.Equals(1,2); gets executed in the Main method the static Constructor is not getting called but when StaticClass.foo(); is executed it calls static constructor and then call the foo method.

我有点困惑,为什么没有得到执行时调用的第一时间 StaticClass.Equals(1,2);

I am little confused as why it didn't get called the the first time when executing StaticClass.Equals(1,2);.

推荐答案

您调用 StaticClass.Equals 是的实际上的只是调用< A HREF =htt​​ps://msdn.microsoft.com/en-us/library/w4hkze5k(v=vs.110).aspx> 的Object.Equals(对象,对象) ,如 StaticClass 不为等于。如果你看一下IL,你会看到,编译器解决了这个电话,只是的Object.Equals(1,2)。如果你不调用它实际上涉及到静态类的方法,它不需要进行初始化。

Your call to StaticClass.Equals is actually just a call to Object.Equals(Object, Object), as StaticClass doesn't provide an applicable overload for Equals. If you look in the IL, you'll see that the compiler has resolved the call to just Object.Equals(1, 2). If you're not calling a method which actually involves the static class, it doesn't need to be initialized.

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

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