【问题标题】:Why does object class need Protected methods? [duplicate]为什么对象类需要受保护的方法? [复制]
【发布时间】:2018-09-26 09:14:34
【问题描述】:

Object 是所有其他类的派生基类。其中,它具有带有受保护访问修饰符的方法(即MemberwiseClone())。
protected 表示该成员可以从声明它的类中访问,也可以从从声明它的类派生的任何类中访问成员。

这是否意味着对于Object,所有受保护的成员实际上都是公开的?如果是,为什么要实施?

【问题讨论】:

  • 它受到保护,因为它是一种危险的方法。只有类本身才能确定浅拷贝是否合适。
  • protected members will be public in fact 这不是真的。公共和受保护之间是有区别的。受保护的成员不能从类外部访问。

标签: c# .net oop


【解决方案1】:

不,这并不意味着它们会公开。这意味着从该类派生的任何类都可以使用受保护的方法。

public class A
{
    private void PrivateMethod() {  /*can be seen only here */ }
    protected void ProtectedMethod() {  /*can be seen here and by anyone deriving from me (A) */ }
    internal void InternalMethod() {  /*can be seen here and by anyone in the same assembly with me. */ }
    public void PublicMethod() {  /*can be seen here and by anyone else. */ }
}

【讨论】:

  • 但是 C# 中的所有类都派生自 object,这使得在这种情况下 protected 与 public 相同。
  • @Bottlehunter 不,除了你自己的类,你不能从对象访问受保护的方法,这正是受保护的意思。
  • 你是对的。抱歉,我没听错。
  • @Bottlehunter np,很高兴这很有意义。
猜你喜欢
  • 2015-05-02
  • 1970-01-01
  • 2019-11-18
  • 2010-10-06
  • 2019-04-25
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 2019-10-27
相关资源
最近更新 更多