Why is the .ctor() created when I compile C# code into IL?

孤街浪徒 提交于 2019-11-30 16:37:42

问题


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

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

What's the use of .method public instance void .ctor() code? It doesn't seem to do anything.


回答1:


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();

without running into errors.




回答2:


This is covered in section 10.11.4 of the C# language spec

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class

Here Hello has no defined constructor hence the compiler inserts the default do nothing constructor which just calls the base / object version




回答3:


A class for which you don't define a constructor gets an implicit public default constructor.

public MyClass()
  :base()
{
}

This only works if the base class has an accessible parameterless constructor.




回答4:


class Hello inherits object, the default generated constructor simply calls the constructor of class object.




回答5:


I would imagine the specification stipulates that since your class itself is not static or abstract, it must expose a default parameterless constructor. This way, other users of whatever library or PE you build can instantiate a copy of your class.

If it didn't have a .ctor, it could be construed as having a private .ctor, I suppose. It's generally pretty vague. But logically, you're right, there is no need for the .ctor in this instance.



来源:https://stackoverflow.com/questions/7235585/why-is-the-ctor-created-when-i-compile-c-sharp-code-into-il

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!