首页 > Windows开发 > 详细

C#关键字中的访问修饰符protected

时间:2015-05-06 14:43:13      阅读:432      评论:0      收藏:0      [点我收藏+]

https://msdn.microsoft.com/zh-cn/library/bcd5672a.aspx

官方的说法The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances.

protected关键字是一个成员访问修饰符。一个protected的成员,一个protected成员,在其所在的类中,可由其派生类的实例访问。

 

可访问性级别的介绍:

https://msdn.microsoft.com/zh-cn/library/ba0a1yw2.aspx

protected :Access is limited to the containing class or types derived from the containing class.

protected关键字:只能由包含的类进行访问,或者从包含该成员的类所派生的类进行访问。

 

疑惑的地方:错误观点我本以为只要是派生类的实例,就可以访问受保护的成员

http://blogs.msdn.com/b/ericlippert/archive/2005/11/09/why-can-t-i-access-a-protected-member-from-a-derived-class.aspx

class Ungulate {

  protected virtual void Eat() { /* whatever */ }
}

class Zebra : Ungulate {
  protected override void Eat() { /* whatever */ }
}

class Giraffe : Ungulate {
  public static void FeedThem() {
    Giraffe g1 = new Giraffe();
    Ungulate g2 = new Zebra();
    g1.Eat(); // fine
    g2.Eat(); // compile-time error "Cannot access protected member"
  }
}

We can call Ungulate.Eat legally from Giraffe,

but we can‘t call the protected method Zebra.Eat from anything except Zebra or a subclass of Zebra.

Since the compiler cannot determine from the static analysis that we are not in this illegal situation, it must flag it as being illegal.

C#关键字中的访问修饰符protected

原文:http://www.cnblogs.com/chucklu/p/4481642.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!