Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?

前端 未结 6 689
自闭症患者
自闭症患者 2020-12-08 23:27

I would like to try this code:

public struct Direction
{
   private int _azimuth;

   public int Azimuth
   {
     get { return _azimuth; }
     set { _azimu         


        
6条回答
  •  無奈伤痛
    2020-12-08 23:50

    This works:

      public Direction(int azimuth)
      {
        _azimuth = azimuth;
      }
    

    From the spec:

    Struct constructors are invoked with the new operator, but that does not imply that memory is being allocated. Instead of dynamically allocating an object and returning a reference to it, a struct constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary.

    Basically, the compiler must see that every field gets initialized in the constructor so that it can copy those values, and it is not willing to examine calls to functions or properties.

提交回复
热议问题