简体   繁体   English

C#类实例字段默认值赋值加默认构造函数等于双赋值?

[英]C# class instance field default value assignment plus default constructor equals double assignment?

I'm new to c# and read that instance fields were initialized before a default constructor call. 我是c#的新手并且读取了在默认构造函数调用之前初始化了实例字段。 Does that mean that they are doubly initialized? 这是否意味着它们被双重初始化?

class MyClass
{
  public int value;

}

Would that mean that value gets the default 0 then the the default constructor is called and assigns 0 again? 这是否意味着该值获得默认值0然后调用默认构造函数并再次分配0?

No, the parameterless constructor created by the compiler doesn't perform an assignment to the field unless you specify a variable initializer. 不,除非指定变量初始值设定项,否则编译器创建的无参数构造函数不会对字段执行赋值。 So in a class like this: 所以在这样的类中:

class Test
{
    int a = 0;
    int b = 1;
    int c;
}

... the generated constructor looks like this in IL: ...生成的构造函数在IL中看起来像这样:

.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       22 (0x16)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.0
  IL_0002:  stfld      int32 Test::a
  IL_0007:  ldarg.0
  IL_0008:  ldc.i4.1
  IL_0009:  stfld      int32 Test::b
  IL_000e:  ldarg.0
  IL_000f:  call       instance void [mscorlib]System.Object::.ctor()
  IL_0014:  nop
  IL_0015:  ret
} // end of method Test::.ctor

Note the assignments to a and b but not c . 注意ab的分配但不是c Normally the difference between explicitly assigning a value of 0 and leaving it to be the default value is not observable, but it's present in the IL. 通常,显式指定值0并将其保留为默认值之间的差异是不可观察的,但它存在于IL中。 (A subclass which decided to call some virtual method before calling the base class constructor could demonstrate the difference, although I suspect that would violate the CLS.) 调用基类构造函数之前决定调用某个虚方法的子类可以证明存在差异,但我怀疑这会违反CLS。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM