C#受保护的字段访问

Yip*_*Yay 9 c# encapsulation private protected

(这个问题是C#访问派生类中受保护成员的后续行动)

我有以下代码片段:

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!";
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 现在,我们知道私有和受保护的字段是私有的并且受类型保护,而不是实例.

  • 我们也知道访问修饰符应该在编译时工作.

  • 所以,这里有一个问题 - 为什么我不能访问类实例的FurColor字段?FoxRedFox RedFox派生自Fox,因此编译器知道它可以访问相应的受保护字段.

  • 另外,正如您所见CorrectPaintFox,我可以访问RedFox类实例的受保护字段.那么,为什么我不能期望Fox类实例中的相同内容呢?

小智 5

简单的原因是:

public void IncorrectPaintFox(Fox anotherFox)
{
    anotherFox = new BlueFox();

    // This one is inaccessible here and results in a compilation error.
    anotherFox.FurColor = "Hey!";
}
Run Code Online (Sandbox Code Playgroud)

现在你没有从内部访问受保护的字段BlueFox,因此编译器不知道运行时类型是什么,它必须始终使这个错误.