我有以下两个类
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 类,我无法理解反编译时的构造函数是空的。认为它与设置支持字段的 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# 6 主构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26689983/