【问题标题】:Is a constructor always present in a class?构造函数总是存在于类中吗?
【发布时间】:2021-03-10 16:09:20
【问题描述】:

当我创建没有构造函数和构造函数的类时,IL 代码不会改变。我认为总是存在构造函数是错误的吗?

namespace Test13
{
    class Human
    {

    }
}    

在下面的 IL 代码中,行 -

IL_0001: call instance void [System.Runtime]System.Object::.ctor()

在不声明构造函数的情况下调用构造函数。

.class private auto ansi beforefieldinit
  Test13.Human
    extends [System.Runtime]System.Object
{

  .method public hidebysig specialname rtspecialname instance void
    .ctor() cil managed
  {
    .maxstack 8

    // [11 9 - 11 23]
    IL_0000: ldarg.0      // this
    IL_0001: call         instance void [System.Runtime]System.Object::.ctor()
    IL_0006: nop

    // [12 9 - 12 10]
    IL_0007: nop

    // [14 9 - 14 10]
    IL_0008: ret

  } // end of method Human::.ctor
} // end of class DecompilationLearn.Human

如果有人能帮我解决这个问题,谢谢。

【问题讨论】:

  • 是的,如果我们不定义一个默认无参数
  • 请注意,静态类没有有任何构造函数。
  • 如果没有构造函数会怎样?您将如何使用(创建一个实例)该类?

标签: c# class oop constructor


【解决方案1】:

简而言之,是的。

如果你自己不提供任何构造函数,编译器会在编译时添加一个公共默认(无参数)的,它会在IL代码中生成。

当你创建一个类的对象时,你在new关键字之后调用那个类的构造函数-

Human human = new Human();

因此,任何可以创建对象的类都必须有构造函数。这就是为什么,如果您不为 Human 类提供构造函数,编译器会提供一个以确保您可以实例化该类,如 documentation here 中所述 -

如果你没有为你的类提供构造函数,C# 会创建一个 默认实例化对象并将成员变量设置为 默认值...

对于静态类有一个例外(正如 @JonSkeet 在 cmets 中提到的那样) - 静态类不能有带有 any 访问修饰符的构造函数。那是因为你不能创建静态类的对象。

你提到的 IL 代码没有生成 -

在不声明构造函数的情况下调用构造函数

相反,它正在调用Human 的基类(System.Object) 的构造函数,并且该调用发生在编译器为您生成的Human 构造函数内。

【讨论】:

    【解决方案2】:

    正如您在“无参数构造函数”部分中正确观察到的那样和MSDN confirms

    如果你没有为你的类提供构造函数,C#会默认创建一个

    【讨论】:

      【解决方案3】:

      如果你没有在 c# 中定义构造函数,C# 编译器会自动在类中创建一个公共的无参数构造函数。

      Constructors - MSDN

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-24
        • 2011-04-11
        • 2014-08-04
        • 2020-08-07
        • 2022-12-18
        • 1970-01-01
        相关资源
        最近更新 更多