Trying to reproduce “must declare a body” compiler

2019-05-24 10:16发布

问题:

I'm trying to reproduce the C# compiler error CS0840 with the exact code that's given in the website:

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();
}

I'm running it on .NET 4.0 using Visual Studio Community 2015. Surprisingly, I cannot reproduce it. Compiler doesn't throw any error:

Why the compiler isn't throwing any error?

回答1:

You're using Visual Studio 2015, which implements C# 6. The fact that you're targeting .NET 4 is irrelevant - most of the C# 6 language features don't depend on framework features at all. The C# 6 code you're using can easily be compiled without reference to any modern CLR or framework features - it could have worked with .NET 1.0 if the language designers had decided to :)

You'll need to set you language level to C# 5 to see an error here. Do that in the project properties / Build / Advanced dialog:

You'll then get this error:

error CS8026: Feature 'readonly automatically implemented properties' is not available in C# 5. Please use language version 6 or greater.

Admittedly that's not the error you actually wanted to see - I think you'll need to use an earlier version of the compiler to get that exact error.



回答2:

I guess it is because you are on Visual Studio 2015 with C# 6 which allows you to specify properties that are only set from the constructor (aka read-only properties).

See the following example:

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!
}