我们可以拥有默认构造函数的主体吗? [英] Can we have a body to a default constructor?

查看:87
本文介绍了我们可以拥有默认构造函数的主体吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

每个类都有一个构造函数.如果程序员定义了那个构造函数,那么它将有一个主体.

但是,对于不是由程序员定义的默认构造函数,它可以具有主体吗?

Hi everyone!

Every class will have a constructor.If programmer defines that contructor then it will have a body.

But for default constructor which was not defined by a programmer can it have a body?

推荐答案

即使是从编译器生成的,默认构造函数也具有主体. 这是由编译器生成的默认构造函数的示例(我使用了 ildasm [ ^ ]以获得IL代码):
Even generated from compiler the default constructor has a body.
Here is an example for a default constructor generated by the compiler (I''ve used ildasm[^] to get the IL code):
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: call instance void [mscorlib]System.Object::.ctor()
    L_0006: ret
}


从上面的IL代码中,您可以轻松地发现对基类的默认构造函数的调用(在本例中为System.Object).
另外,如果您的类是static,则不会生成任何构造函数.

:)


From the IL code above you can easily spot the call to the default constructor of the base class (in our case System.Object).
Additionally if your class is static no constructors will be generated.

:)


嗨laxmi_hemu,

我不确定我是否完全理解这个问题,但是在C#中,如果您未定义默认构造函数,则将在类中为您隐式定义默认构造函数.它将成员变量初始化为其默认值.

因此,即使您有一个没有定义构造函数的类,您仍然可以像

hi laxmi_hemu,

I am not sure I fully understand the question, but in C# if you don''t define a default constructor a default constructor will be implicitly defined for you in the class. It initialises the member variables to their default values.

So even if you have a class without a constructor defined, you can still fo something like

MyClass myClass = new MyClass();



MSDN的此链接应为您提供更多见解. MSDN:构造函数 [



This link from MSDN should give you more insight. MSDN: Constructors[^]

Hope this helps :)
Dave


不带参数的构造函数称为默认构造函数,其中将包含一些编码部分,具体取决于应用程序的需求.
The constructor which takes no argument is called default constructor.And it wil contains some coding part in it, which depends on the requirement of the application.


这篇关于我们可以拥有默认构造函数的主体吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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