使用结构和属性时没有编译错误
Absence of compilation error when working with struct and properties
考虑 C# 中的以下结构:
public struct TestStruct
{
public int Number { get; set; }
public TestStruct(int num)
{
Number = num;
}
}
我非常熟悉如果有人试图编译它会发生的编译错误(this and that 问题提供了一个例子)。
不过,我最近注意到这种结构在 Visual Studio 2015 年编译得非常完美。
我找不到任何包含上述行为的编译器更改日志。任何人都可以提供有关在哪里可以找到此类信息的任何指导吗?我发现提到了类似的东西 here。
此外,有关编译器错误的页面 CS0188 指出:
Auto-implemented properties should be avoided in structs because they have no backing field and therefore cannot be initialized in any way from the constructor.
但是,我无法观察到无法从构造函数中初始化 属性。
这是 C#6 中的新功能(这是您将在 VS2015 中默认使用的)。该编译器错误的描述也不完全正确。 Auto-properties 一直都有一个支持字段,它只是由编译器生成,无法通过代码直接访问。所以有点误导。
C# 中对 auto-property 初始化的更改现在允许编译器生成代码来设置支持字段,而不是尝试在构造函数中调用 setter 方法。这也使得创建不可变结构变得更加容易:
public struct Foo
{
public string ReadOnlyString { get; }
public Foo( string prop )
{
ReadOnlyString = prop;
}
}
考虑 C# 中的以下结构:
public struct TestStruct
{
public int Number { get; set; }
public TestStruct(int num)
{
Number = num;
}
}
我非常熟悉如果有人试图编译它会发生的编译错误(this and that 问题提供了一个例子)。
不过,我最近注意到这种结构在 Visual Studio 2015 年编译得非常完美。
我找不到任何包含上述行为的编译器更改日志。任何人都可以提供有关在哪里可以找到此类信息的任何指导吗?我发现提到了类似的东西 here。
此外,有关编译器错误的页面 CS0188 指出:
Auto-implemented properties should be avoided in structs because they have no backing field and therefore cannot be initialized in any way from the constructor.
但是,我无法观察到无法从构造函数中初始化 属性。
这是 C#6 中的新功能(这是您将在 VS2015 中默认使用的)。该编译器错误的描述也不完全正确。 Auto-properties 一直都有一个支持字段,它只是由编译器生成,无法通过代码直接访问。所以有点误导。
C# 中对 auto-property 初始化的更改现在允许编译器生成代码来设置支持字段,而不是尝试在构造函数中调用 setter 方法。这也使得创建不可变结构变得更加容易:
public struct Foo
{
public string ReadOnlyString { get; }
public Foo( string prop )
{
ReadOnlyString = prop;
}
}