What is the difference between instantiation in constructor or in field definition?

白昼怎懂夜的黑 提交于 2019-12-30 10:35:34

问题


What is the difference between this:

public class Foo {
    private Bar bar;
    public Foo() { bar = new Bar(); }
}

and this:

public class Foo {
    private Bar bar = new Bar();
    public Foo() { }
}

回答1:


The difference is that in the second case field initialization happens before this/base constructor while in the first case initialization happens inside the constructor.




回答2:


The CLR does not support initializing fields like this. To make it work, the C# compiler rewrites your constructor. The IL looks like this:

  IL_0000:  ldarg.0
  IL_0001:  newobj     instance void ConsoleApplication1.Bar::.ctor()
  IL_0006:  stfld      class ConsoleApplication1.Bar ConsoleApplication1.Foo::bar
  IL_000b:  ldarg.0
  IL_000c:  call       instance void [mscorlib]System.Object::.ctor()
  IL_0011:  ret

Note that the Bar constructor is called before the Foo base constructor. Which is the difference with your other snippet, there the Foo base constructor is called afterward. This will rarely make a difference, unless the field is inherited and the base class constructor does something with it.

Or if field initializers depend on each other, they are initialized in strict textual order. You can control the order by doing it explicitly in the constructor.




回答3:


Stating the obvious a bit, but with the second approach there's no need for a constructor.




回答4:


There is no difference, because a compiler places all field definitions before constructor's code. So in IL-code both variants look equally.




回答5:


To add to Darin Dimitrov's answer, initialising the fields in line is a good idea if you have several constructor overloads, and you don't want to call other overloaded constructors for some reason.



来源:https://stackoverflow.com/questions/3381715/what-is-the-difference-between-instantiation-in-constructor-or-in-field-definiti

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