码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-05-06 14:45:21      阅读:180      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!