<分区>
(此问题是 C# accessing protected member in derived class 的后续问题)
我有以下代码片段:
public class Fox
{
protected string FurColor;
private string furType;
public void PaintFox(Fox anotherFox)
{
anotherFox.FurColor = "Hey!";
anotherFox.furType = "Hey!";
}
}
public class RedFox : Fox
{
public void IncorrectPaintFox(Fox anotherFox)
{
// This one is inaccessible here and results in a compilation error.
anotherFox.FurColor = "Hey!";
}
public void CorrectPaintFox(RedFox anotherFox)
{
// This is perfectly valid.
anotherFox.FurColor = "Hey!";
}
}
现在,我们知道 private and protected fields are private and protected for type, not instance.
我们还知道访问修饰符应该在编译时起作用。
所以,问题来了 - 为什么我无法访问
RedFox< 中
?Fox
类实例的FurColor
字段RedFox
派生自Fox
,因此编译器知道它可以访问相应的 protected 字段。此外,正如您在
CorrectPaintFox
中所见,我可以访问RedFox
类实例的 protected 字段。 那么,为什么我不能对Fox
类实例有同样的期望?