[英]Why does this C# code with an an undeclared get body build? And how can I make the compiler throw an error on this?
To my surprise, the following code builds and runs fine: 令我惊讶的是,以下代码可以构建并正常运行:
private abstract class MyParent
{
public abstract bool MyBool { get; }
}
private class MyChild : MyParent
{
public override bool MyBool { get; } //no body declared
}
[TestMethod]
public void MyTestMethod()
{
var mc = new MyChild();
Assert.IsFalse(mc.MyBool);
}
I don't get any warnings either. 我也没有收到任何警告。 The test even passes.
测试甚至通过。 I wouldn't expect this to compile because the
MyChild
class doesn't declare a body for the overridden MyBool
getter. 我不希望它会编译,因为
MyChild
类没有为重写的MyBool
getter声明主体。 I tried marking the MyChild
class sealed
, but it still compiled. 我尝试将
MyChild
类标记为sealed
,但仍可以编译。 My first question is simply, why is the MyChild
class not required to provide a body for the MyBool
getter? 我的第一个问题很简单,为什么不要求
MyChild
类为MyBool
getter提供主体?
I found that I had a problem like this in my code because my build server reported a compiler error that said: 我发现我的代码中存在这样的问题,因为我的构建服务器报告了一个编译器错误,指出:
'MyChild.MyBool.get' must declare a body because it is not marked abstract or extern.
“ MyChild.MyBool.get”必须声明一个主体,因为它没有被标记为抽象或外部。 Automatically implemented properties must define both get and set accessors.
自动实现的属性必须定义get和set访问器。
The build server must be using some settings that prevented this same code from compiling. 构建服务器必须使用某些设置来阻止编译相同的代码。 My second question is: what settings can I check to ensure that the compiler gives me this warning when I try to compile this code?
我的第二个问题是:当我尝试编译此代码时,可以检查哪些设置以确保编译器向我发出此警告?
I wouldn't expect this to compile because the
MyChild
class doesn't declare a body for the overriddenMyBool
getter.我不希望它会编译,因为
MyChild
类没有为重写的MyBool
getter声明主体。
That is because it is perfectly fine. 那是因为它很好。 The
MyBool
property has an (implicit) setter, but that is only available to the constructor. MyBool
属性具有一个(隐式)设置器,但仅对构造方法可用。 This is a new feature to the C# 6 compiler, so your build server needs the same version of the compiler to make this work. 这是C#6编译器的新功能,因此您的构建服务器需要相同版本的编译器才能完成此工作。
There is no need to throw an exception, or anything like that. 不需要抛出异常或类似的东西。 If you want a
set
to be declared, just make sure to add it to the property definition in the base class. 如果要声明一个
set
,只需确保将其添加到基类的属性定义中即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.