为什么在将C#代码编译为IL时创建.ctor()? [英] Why is the .ctor() created when I compile C# code into IL?
问题描述
使用这个简单的C#代码,我运行 csc hello.cs;。 ildasm /out=hello.txt hello.exe
。
With this simple C# code, I run csc hello.cs; ildasm /out=hello.txt hello.exe
.
class Hello
{
public static void Main()
{
System.Console.WriteLine("hi");
}
}
这是ildasm的IL代码。
This is the IL code from ildasm.
.class private auto ansi beforefieldinit Hello
extends [mscorlib]System.Object
{
.method public hidebysig static void Main() cil managed
{
.entrypoint
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "hi"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method Hello::Main
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Hello::.ctor
} // end of class Hello
.method公共实例void .ctor()
代码的用途是什么?
What's the use of .method public instance void .ctor()
code? It doesn't seem to do anything.
推荐答案
它是默认的无参数构造函数。你是对的;它什么也没做(除了传递给基本的 Object()
构造函数之外,它本身也没有任何特殊作用)。
It's the default parameterless constructor. You're correct; it doesn't do anything (besides passing on to the base Object()
constructor, which itself doesn't do anything special either anyway).
如果未定义任何其他构造函数,则编译器始终为非静态类创建默认构造函数。然后,将任何成员变量初始化为默认值。这样就可以做到
The compiler always creates a default constructor for a non-static class if there isn't any other constructor defined. Any member variables are then initialized to defaults. This is so you can do
new Hello();
而不会出错。
这篇关于为什么在将C#代码编译为IL时创建.ctor()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!