[英]Why static constructor not called before first call to class method
According to Jon Skeet's artice C# and beforefieldinit and discussion in When is a static constructor called in C#?根据 Jon Skeet 的文章C# 和 beforefieldinit以及When is a static constructor called in C#? static constructor must be called before first call to a method of the class.
static 必须在第一次调用 class 的方法之前调用构造函数。
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");
}
}
}
I am debugging the above code using the Visual Studio Debugger.我正在使用 Visual Studio 调试器调试上述代码。 When the statement
StaticClass.Equals(1,2);
当声明
StaticClass.Equals(1,2);
gets executed in the Main method the static Constructor is not getting called but when StaticClass.foo();
在 Main 方法中执行 static 构造函数没有被调用但是当
StaticClass.foo();
is executed it calls static constructor and then call the foo method.执行它调用static构造函数,然后调用foo方法。
I am little confused as why it didn't get called the the first time when executing StaticClass.Equals(1,2);
我有点困惑,为什么在执行
StaticClass.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
. 您对
StaticClass.Equals
的调用实际上只是对Object.Equals(Object, Object)
的调用,因为StaticClass
不为Equals
提供适用的重载。 If you look in the IL, you'll see that the compiler has resolved the call to just Object.Equals(1, 2)
. 如果查看IL,您将看到编译器已经解析了对
Object.Equals(1, 2)
的调用。 If you're not calling a method which actually involves the static class, it doesn't need to be initialized. 如果您没有调用实际涉及静态类的方法,则不需要初始化它。
The execution of a static constructor is triggered by the first of the following events to occur: static 构造函数的执行由以下第一个事件触发:
An instance of the class is created.创建 class 的实例。 Any of the static members of the class are referenced.
引用了 class 的任何 static 成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.