C# 保护域访问

标签 c# private encapsulation protected

<分区>

(此问题是 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 类实例有同样的期望?

最佳答案

原因很简单:

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

    // This one is inaccessible here and results in a compilation error.
    anotherFox.FurColor = "Hey!";
}

现在您不是从 BlueFox 中访问 protected 字段,因此由于编译器不知道运行时类型是什么,它必须始终将其设为错误。

关于C# 保护域访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10659086/

相关文章:

c++ - 是否有私有(private)使用名称=类型;

postgresql - 我应该如何提取 Postgres 函数中的重复逻辑?

java - 在同一个类的方法中使用封装getter

namespaces - Polymer组件不封装javascript

c# - 如何在 Linq 中循环遍历数据表?

c# - 从 Xaml 绑定(bind) RichTextBox 的文本

c# - 在插入中使用来自另一个表的值

c# - Microsoft.Exchange.WebServices.Data.ServiceResponseException : Connection did not succeed. 稍后重试

http - 通过 HTTP 获取私有(private) GitLab 仓库

java - 设计决策 : Why and when to make an interface private?