简单地说:访问实例的受保护成员被视为公共访问,即使您尝试从派生类中这样做。因此,它被拒绝了。
这里和那里有很多答案,但没有一个让我明白“为什么我不能从孩子那里访问父类的受保护成员”。以上是我在阅读了这些令人困惑的答案后再次查看我的代码后所理解的。
例子:
class Parent
{
protected int foo = 0;
}
// Child extends from Parent
class Child : Parent
{
public void SomeThing(Parent p)
{
// Here we're trying to access an instance's protected member.
// So doing this...
var foo = p.foo;
}
}
// (this class has nothing to do with the previous ones)
class SomeoneElse
{
public void SomeThing(Parent p)
{
// ...is the same as doing this (i.e. public access).
var foo = p.foo++;
}
}
你会认为你可以访问,p.foo
因为你在一个子类中,但你是从一个实例访问它,这就像一个公共访问,所以它被拒绝了。
您可以protected
从类中访问成员,而不是从实例中访问成员(是的,我们知道这一点):
class Child : Parent
{
public void SomeThing()
{
// I'm allowed to modify parent's protected foo because I'm
// doing so from within the class.
foo++;
}
}
最后,为了完整起见,只有在同一个类中这样做时,您实际上才能访问实例protected
甚至成员:private
class Parent
{
protected int foo = 0;
private int bar = 0;
public void SomeThing(Parent p)
{
// I'm allowed to access an instance's protected and private
// members because I'm within Parent accessing a Parent instance
var foo = p.foo;
p.bar = 3;
}
}