在 C# 中,嵌套类可以访问包含类的私有(private)成员。
为什么我不能覆盖这些成员?为什么编译器会出错?
private abstract class InheritanceTest
{
public virtual object Property
{
get { return null; }
private set { }
}
public class Child : InheritanceTest
{
public override object Property
{
get { return null; }
private set { base.Property = null; } // the base.Property = null statement here is just to show that there isn't an error message for accesing a parent private member.
}
}
}
我得到的唯一错误信息是:
'Program.InheritanceTest.Child.Property.set': cannot override inherited member 'Program.InheritanceTest.Property.set' because it is not marked virtual, abstract, or override
编译器显然出错了,因为整个属性都被标记为虚拟的。 get 方法可以覆盖继承的成员。
C#规范的这一部分,只有错误信息是错误的吗?还是应该允许这样做?
我缺少规范的哪一部分? (或者缺少编译器?)
最佳答案
私有(private)虚拟方法和属性不能被覆盖:
You cannot use the virtual modifier with the static, abstract, private, or override modifiers. virtual (C# Reference)
关于c# - 为什么我不能覆盖嵌套类中的私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9050011/