简体   繁体   English

为什么允许在密封类中编写受保护的成员?

[英]Why is it allowed to write protected members in sealed class?

密封类是一个不能继承的类,为什么允许在密封类中编写受保护的成员

Because Microsoft decided it to not be an error. 因为微软认为这不是一个错误。

I agree that it makes no sense to declare a protected member in a sealed class. 我同意在sealed类中声明protected成员是没有意义的。 Using protected on a member in a sealed class is the same as having a private member sealed类中使用protected成员与拥有private成员相同

Therefore you will get the following compiler warning: https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/7x8ekes3(v=vs.90) 因此,您将收到以下编译器警告: https//docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/7x8ekes3(v = vs.90)

Sealed classes can still have inherited Protected members, so to me it makes sense. 密封类仍然可以继承受保护的成员,所以对我来说这是有道理的。 Maybe the designers did this to allow inheritance without needing to make a special compiler case. 也许设计者这样做是为了允许继承而不需要编写特殊的编译器案例。

public class Foo
{
    protected virtual string Name { get; set; } = "Foo";
}

public sealed class Bar : Foo
{
    protected override string Name { get; set; } = "Bar";
}

Update: From Eric Lippert in 2009 : 更新:来自Eric Lippert在2009年

The language design notes document that the decision to make introducing a virtual method into a sealed type an error was made on the 18th of October, 1999, but does not give any justification for the decision. 语言设计说明文件表明,在1999年10月18日做出了将虚拟方法引入密封型错误的决定,但没有给出任何理由。 I can find nowhere in the notes that justifies why introducing a new protected member ought to be legal. 我可以在笔记中找不到任何理由说明为什么引入一个新的受保护成员应该是合法的。 My best guess: this was probably simply an oversight in the first version, and then it became a breaking change to ever fix it. 我最好的猜测:这可能只是第一个版本中的一个疏忽,然后它变成了一个突破性的变化,永远修复它。 – Eric Lippert - Eric Lippert

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM