我有以下两节课

public class Point(int x, int y)
    {
        public int X { get; } = x;
        public int Y { get; } = y;
    }



    public class Point2
    {
        public int X { get; private set; }
        public int Y { get; private set; }

        public Point2(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }


并使用jetbrains dotpeek反编译时得到以下信息:

namespace ConsoleApplication1
{
  public class Point
  {
    public int X
    {
      get
      {
        return this.\u003CX\u003Ek__BackingField;
      }
    }

    public int Y
    {
      get
      {
        return this.\u003CY\u003Ek__BackingField;
      }
    }

    public Point(int x, int y)
    {
    }
  }
}




namespace ConsoleApplication1
{
  public class Point2
  {
    public int X { get; private set; }

    public int Y { get; private set; }

    public Point2(int x, int y)
    {
      this.X = x;
      this.Y = y;
    }
  }
}


对于使用Primary构造函数的Point类,我无法理解反编译时的ctor为空。以为它将与设置后备字段的Point2相同。
有人可以解释吗?

最佳答案

之所以看不到它,是因为初始化由编译器生成的后备字段的代码以及默认情况下dotPeek不会显示由编译器生成的代码。但是,如果启用“显示编译器生成的代码”,则会看到以下内容:

public class Point
{
    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly int \u003CX\u003Ek__BackingField;
    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly int \u003CY\u003Ek__BackingField;

    public int X
    {
      get
      {
        return this.\u003CX\u003Ek__BackingField;
      }
    }

    public int Y
    {
      get
      {
        return this.\u003CY\u003Ek__BackingField;
      }
    }

    public Point(int x, int y)
    {
      this.\u003CX\u003Ek__BackingField = x;
      this.\u003CY\u003Ek__BackingField = y;
      base.\u002Ector();
    }
}

关于c# - C#6主ctor,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26689983/

10-13 07:27