试图重现“必须声明一个正文”编译器错误
我正在尝试使用网站中给出的确切代码重现C#编译器错误CS0840 :
class Test36 { public int myProp { get; } // CS0840 // to create a read-only property // try the following line instead public int myProp2 { get; private set; } } public Form1() { InitializeComponent(); Test36 test = new Test36(); }
我使用Visual Studio Community 2015在.NET 4.0上运行它。令人惊讶的是,我无法重现它。 编译器不会抛出任何错误:
为什么编译器没有抛出任何错误?
您正在使用实现C#6的Visual Studio 2015.您针对.NET 4的事实无关紧要 – 大多数C#6语言function根本不依赖于框架function。 您正在使用的C#6代码可以轻松编译,而无需参考任何现代CLR或框架function – 如果语言设计者决定:)它可以与.NET 1.0一起使用:)
您需要将语言级别设置为C#5才能在此处查看错误。 在项目属性/构建/高级对话框中执行此操作:
然后你会收到这个错误:
错误CS8026:function’只读自动实现的属性’在C#5中不可用。请使用语言版本6或更高版本。
不可否认,这不是您真正想要看到的错误 – 我认为您需要使用早期版本的编译器才能获得确切的错误。
我想这是因为你在Visual Studio 2015上使用C#6,它允许你指定仅从构造函数设置的属性(也称为只读属性 )。
请参阅以下示例:
class Test { public Test() // <-- this one does compile since it is the constructor { MyProp = 1; } public void SomeMethod() // <-- this one doesn't compile { MyProp = 1; } public int MyProp { get; } // <-- no CS0840 any more! }